I am new to AngularJS. Here's my question.
I have a page-level variable like this var isStateA = false
. I have assigned this variable to my controllers variable like this:
var isStateA = false;
app.controller('AController',function($scope){
$scope.shouldShow = isStateA;
});
app.controller('BController',function($scope){
$scope.shouldShow = !isStateA;
});
The shouldShow
properties are bind to ng-show
accordingly.
The expected behavior is when I change isStateA
to be true
. The values in scope of the two controller should change, and as a result, they should perform show/hide logic.
But this is not happening with my code above. I am wondering if there's a way to do it? Like when the isStateA
value changed, notify related properties to apply the latest value?
Thank you
You are getting this wrong because you don't understand
AngularJS knows that values have changed in your application because of watchers. Watchers are assigned in many places, but in your case when you use $scope.shouldShow in the template. Changing the value of $scope.shouldShow will be picked up by angular and work, but changing isStateA will not, and that's because they are not the same variable. Here is the correct solution:
// Your code
app.service('stateAService', function() {
this.isStateA = false;
})
app.controller('AController', function($scope, stateAService) {
$scope.stateAService = stateAService;
})
app.controller('BController', function($scope, stateAService) {
$scope.stateAService = stateAService;
})
// Template, controller A
<div ng-show="stateAService.isStateA">
</div>
// Template, controller B
<div ng-show="!stateAService.isStateA"></div>
// Some code, anywhere else in your app
app.controller('WhateverController', function($scope, stateAService) {
this.hideBAndShowA = function() {
stateAService.isStateA = true;
// The change to stateAService gets picked up by the watchers, all good
}
})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments