Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS: ng-click scope set doesn't work in ng-if

Tags:

angularjs

Today, I have seen a bug in angularjs:

When you try to set a scope value directly in a ng-click, it doesn't work when your ng-click is in a ng-if which test the same scope value -> http://jsfiddle.net/9j2TL/26/

angular.module('test', [])
.controller('testCtrl', function($scope) {
    $scope.step = 1;

    $scope.setStep = function(step) {
         $scope.step = step;  
    };
});

<div ng-app="test">
<div ng-controller="testCtrl">
    <ul class="timeline">
        <li>
            <div class="block-submit">
                <button class="btn btn-primary btn-lg" ng-click="step = 2">Without ngif block</button>
            </div>
        </li>

        <li ng-if="step > 1">
            <div class="block-submit">
                <button class="btn btn-primary btn-lg" ng-click="step = 3">with ngif block</button>
            </div>
        </li>

        <li ng-if="step > 1">
            <div class="block-submit">
                <button class="btn btn-primary btn-lg" ng-click="setStep(3)">With ngif block and scope function</button>
            </div>
        </li>
    </ul>
    <p>
        step value : {{ step }}
    </p>
</div>
</div>

To solve it, you should create a scope function...

If somebody have a explication for this problem, I would be happy to understand it !

thx :)

like image 596
Geoffrey Avatar asked Feb 28 '14 15:02

Geoffrey


1 Answers

I don't think this is a bug. You are just auto-creating properties and confusing scopes in the view.

Updated Fiddler.

This does work:

<li ng-if="step > 1">
    <div class="block-submit">
        <button class="btn btn-primary btn-lg" ng-click="$parent.step = 3">with ngif block</button>
    </div>
</li>

This is happening because self inside of the ng-if is creating a new scope.

like image 132
Davin Tryon Avatar answered Oct 01 '22 09:10

Davin Tryon