Joe82 Joe82 - 4 months ago 12x
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
value to false,
should output
. In order to change the scope value, I use ng-click:

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

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


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.


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

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