0

Controller

function MainController($scope, $rootScope, $location, $route) {
    $scope.EditMode = false;

    $scope.Click = function () {
        $scope.EditMode = !$scope.EditMode;
    };
}

HTML

<button ng-if="!EditMode" ng-click="$parent.EditMode = !$parent.EditMode">Button1</button>
<button ng-if="!EditMode" ng-click="EditMode = !EditMode">Button2</button>
<button ng-if="!EditMode" ng-click="Click()">Button3</button>

Button1 - work

Button2 - NOT work

Button3 - Work

Why Button2 not work?

Alexandr Sulimov
  • 1,894
  • 2
  • 24
  • 48

2 Answers2

3

When you add the directive ng-if it create new scope. The new scope have the same values from the parent scope. That why button1 and button3 works.

Buttons2 not work because when you do EditMode = !EditMode it create new variable named EditMode in the new scope.

You have several options to fix it. The most simple one is to replace all ng-if with ng-show

Solution #1:

<button ng-show="!EditMode" ng-click="$parent.EditMode = !$parent.EditMode">Button1</button>
<button ng-show="!EditMode" ng-click="EditMode = !EditMode">Button2</button>
<button ng-show="!EditMode" ng-click="Click()">Button3</button>

Solution #2:

Make EditMode as object. And keep your ng-if This way the new scope will not override the parent scope.

function MainController($scope, $rootScope, $location, $route) {
    $scope.EditMode = {value:false};

    $scope.Click = function () {
        $scope.EditMode.value = !$scope.EditMode.value;
    };
}

<button ng-if="!EditMode.value" ng-click="EditMode.value = !EditMode.value">Button1</button>
<button ng-if="!EditMode.value" ng-click="EditMode.value = !EditMode.value">Button2</button>
<button ng-if="!EditMode.value" ng-click="Click()">Button3</button>

More info:

Solution #1:

Solution #2:

Community
  • 1
  • 1
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
0

Because an ngIf defines its own scope, which prototypically inherits from its parent scope (just like ngRepeat). So, when you change the value of a field inside an ngIf, you change it in the ngIf scope, and not in its parent scope.

Mayur Randive
  • 633
  • 1
  • 10
  • 20
  • https://github.com/angular/angular.js/wiki/Understanding-Scopes read this .. It will help you to understand the scope concept in details – Mayur Randive Jul 11 '16 at 18:11