【发布时间】:2021-12-19 08:47:16
【问题描述】:
当我的复选框被选中时,会打开一个对话框,当我单击取消时,复选框应该被取消选中。
我无法做到这一点。
如果在对话框中选择“否”,则复选框应设置为之前的状态(请参阅if 语句)。
但是,设置复选框的模型$scope.canSupportAccess 似乎对在此函数内检查复选框没有影响。
我已经测试了$scope.canSupportAccess 是否能够更新复选框,通过使用true 和false 对其进行初始化,并且可以看到它确实选中或取消选中复选框。
我注意到我必须将canSupportAccess 作为参数传递给函数,因为$scope.canSupportAccess 不会在updateSupportAccess() 内部更新,即使$scope.canSupportAccess 是模型并且updateSupportAccess() 在复选框更改时被触发。
为什么$scope.canSupportAccess在函数内部不起作用,如何更新updateSupportAccess()函数内部的复选框?
这是为了避免 updateSupportAccess() 被永远递归调用而设计的吗?
如果是这样,解决方法是什么?
这是我的代码:
export default function (app) {
app.controller('userDetailCtrl', [
'shell',
'$scope',
function (shell, $scope) {
$scope.canSupportAccess = false;
$scope.updateSupportAccess = function (canSupportAccess) {
if (canSupportAccess) {
shell.confirmBox('Allow Access',
'Allow access?',
'YesNo', true)
.result
.then(function (result) {
if (result === "yes") {
$scope.canSupportAccess = true;
} else {
$scope.canSupportAccess = false;
}
});
} else {
shell.confirmBox('Remove Access',
'Revoke access?',
'YesNo')
.result
.then(function (result) {
if (result === "yes") {
$scope.canSupportAccess = false;
} else {
$scope.canSupportAccess = true;
}
});
}
}
}]
);
}
和 HTML:
<input type="checkbox"
id="supportAccess"
ng-change="updateSupportAccess(canSupportAccess)"
ng-model="canSupportAccess" />
<label for="supportAccess">
Allow access.
</label>
【问题讨论】:
-
听起来有两个不同的
canSupportAccess属性存在于不同的范围内,这是 AngularJS 中非常常见的问题。尝试使您的属性至少与$scope分开一层并且不直接附加(例如$scope.access = { canSupport: false })。跟随"controller as" syntax best practice 可靠地避免了这个问题。 StackBlitz's AngularJS demo templates 如果您想玩弄这个约定,请为它建模。 -
@JacobStamm 非常感谢。这解决了问题!把它写成答案,我会接受的。
标签: javascript html angularjs checkbox