When my checkbox is checked, a dialog is opened and when I click cancel, the checkbox should be unchecked.
I can't get this to happen.
The checkbox should be set to its previous state if "no" is selected on the dialog (see the if
statements).
However, it seems as though setting the model for the checkbox, $scope.canSupportAccess
, has no effect on the checking of the checkbox inside this function.
I have tested whether or not $scope.canSupportAccess
is able to update the checkbox at all, by initializing it with true
and false
, and can see that it does indeed check or uncheck the checkbox.
I noticed I have to pass in canSupportAccess
as an argument to the function, because $scope.canSupportAccess
is not updated inside updateSupportAccess()
even though $scope.canSupportAccess
is the model and updateSupportAccess()
is triggered when the checkbox changes.
Why does $scope.canSupportAccess
have no effect inside the function, and how can I update the checkbox inside the updateSupportAccess()
function?
Is this by design, to avoid the updateSupportAccess()
being called recursively forever?
If so, what is the work around?
Here's my code:
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;
}
});
}
}
}]
);
}
and the HTML:
<input type="checkbox"
id="supportAccess"
ng-change="updateSupportAccess(canSupportAccess)"
ng-model="canSupportAccess" />
<label for="supportAccess">
Allow access.
</label>
CodePudding user response:
This is being caused by two different canSupportAccess
properties that live in different scopes, a really common problem in AngularJS. Try making your property at least one layer separated from $scope and not directly attached (e.g. $scope.access = { canSupport: false }
). Following the "controller as" syntax best practice reliably avoids this issue, and for an example of this convention in action where you can play with it, see StackBlitz's AngularJS demo templates.
See this popular SO answer on the topic of prototypal inheritance in AngularJS for a deep dive: https://stackoverflow.com/a/14049482/4028303