2

We have some code in an ng-click that broke with version 1.2.0-rc.3 because the value in the scope hasn't been updated from the click. Here's a dumbed down version:

HTML:

<div ng-app="" ng-controller="MyCtrl">
    <input type="checkbox" ng-model="checkAll" ng-click="allChecked()"/>
    <input type="checkbox" ng-model="check1"/>
    <input type="checkbox" ng-model="check2"/>
    <input type="checkbox" ng-model="check3"/>
    <input type="checkbox" ng-model="check4"/>
    <input type="checkbox" ng-model="check5"/>
    <p/>
    All: {{checkAll}}<br/>
    1: {{check1}}<br/>
    2: {{check2}}<br/>
    3: {{check3}}<br/>
    4: {{check4}}<br/>
    5: {{check5}}<br/>
</div>

JavaScript:

function MyCtrl($scope)
{
    $scope.allChecked = function() {
        console.log($scope.checkAll);
        if ($scope.checkAll)
        {

            $scope.check1 = true;
            $scope.check2 = true;
            $scope.check3 = true;
            $scope.check4 = true;
            $scope.check5 = true;
        }
        else
        {
            $scope.check1 = false;
            $scope.check2 = false;
            $scope.check3 = false;
            $scope.check4 = false;
            $scope.check5 = false;
        }
    }
}

Fiddle with 1.2.0-rc.2: http://jsfiddle.net/73E26/

Now with the same exact setup for 1.2.0-rc.3 (http://jsfiddle.net/LZR6j/), it now longer works as expected. $scope.checkAll is false, even though it is checked. So, the model isn't getting updated before the click listener is called like it was with 1.2.0-rc.2. What changed that is causing this? I've found that I can make this work by using ng-change instead of ng-click (http://jsfiddle.net/8VV7N/), but I want to understand what is going on so I base future decisions on it. Can anyone shed some light this?

dnc253
  • 39,967
  • 41
  • 141
  • 157

1 Answers1

0

The problem is that ng-click and ng-model have ambiguous priority and if you define them on the same element, it is unclear in what order will they be fired.

See this question for instance: Clicking a checkbox with ng-click does not update the model

Community
  • 1
  • 1
musically_ut
  • 34,028
  • 8
  • 94
  • 106
  • Thank you for the answer. So what's the difference between `ng-click` and `ng-change` that makes `ng-change` work? Or is it just by chance that it is working like `ng-click` was? – dnc253 Nov 13 '13 at 22:29
  • I would guess that it was by chance that they were working, or perhaps because `ng-change` sets a `$watch` on the `expression` for `ng-model` and that `$watch` is fired only after `ng-model` has processed the value (setting it to the correct value `false`). However, in my experience, it is best to avoid such arrangements. – musically_ut Nov 13 '13 at 22:41