Alexandr Sulimov Alexandr Sulimov - 11 months ago 38
AngularJS Question

Angular JS what is current scope?


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

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


<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?


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: