Joe82 Joe82 - 6 months ago 18
AngularJS Question

AngularJS - change variable value with if else statement when scope changes

I have a variable that I want to change when another scope changes its value.

$scope.switch = true;

var thing;
if ($scope.switch == false) {
thing = "givesFalse";
}
else {
thing = "givesTrue";
};
this.thingscope = thing;


So when I change
$scope.switch
value to false,
this.thingscope
should output
givesFalse
. In order to change the scope value, I use ng-click:

<div ng-controller="myCtrl as myCtrl" ng-app="myApp">
{{myCtrl.thingscope}}
<br>
<a ng-click="switch = !switch">{{switch}}</a>
</div>


But even that I can see that the scope does update, the variable
thing
doesn't seem to update at the same time. You can see the working plunkr here. Thanks in advance!

Answer

The main point is that your Controller's code will be executed only once when your Controller is instanciated. If you want it to respond to changes, you'll need to use $watch.

$scope.$watch('switch', function(newSwitchValue, oldSwitchValue) {
  if ($scope.switch == false) {
    $scope.thing = "givesFalse";
  }
  else {
    $scope.thing = "givesTrue";
  }
});

In a real-world app where the architecture and performance matters, I would advise you to call directly a function from the ng-click.

ng-click="onClickSwitch()"

Then define the function onClickSwitch() in the $scope.

$scope.onClickSwitch = function() {
    $scope.switch = !$scope.switch;
    [code as above]
}