Reputation: 1924
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?
Upvotes: 0
Views: 84
Reputation: 24590
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
<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>
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>
Upvotes: 3
Reputation: 643
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.
Upvotes: 0