0

I am unable to understand the following behaviour:

Here is my angular code:

(function(){
'use strict';
angular.module('myMod',[ ])
    .controller('abc',function($scope) {
        $scope.products = products;

        $scope.printProducts = function(){
            for(var index in $scope.products){
              console.log($scope.products[index].key + " " + $scope.products[index].check);
            }
        };

    });

   var products = [{key:'HERO',check:0}, {key:'MARUTI',check:0}, {key:'TATA',check:0}]; 
   }());

Here is my HTML:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body ng-app="myMod">
    <div ng-controller="abc">
       <div ng-repeat="product in products">
        <label><input type="checkbox" ng-true-value='1' ng-false-value='0' ng-model='product.check' ng-click="printProducts()">{{product.key}}{{product.check}}</label>
      </div>
    </div>  
<!-- scripts section -->
<script type="text/javascript" src = "angular.js"></script>
<script type="text/javascript" src= "basic.js"></script>
</body>
</html>

So here I am trying to bind to a property of an object 'check' in this case to the output of my checkbox which when selected returns 1 and when unselected gives a value of 0. However, when I am printing the property in console inside the for loop I am getting unexpected behaviour.

For example : when I selected "HERO" I got this output: HERO 0 -- > should be 1 here MARUTI 0 TATA 0

Now when I selected Maruti I got : HERO 1 MARUTI 0 -- > should be 1 here TATA 0

Can anyone please explain whats going on here ? Link to fiddle(thought u cannot see console output) http://jsfiddle.net/k2wfyj6e/

PSL
  • 123,204
  • 21
  • 253
  • 243
JackSparrow
  • 187
  • 1
  • 2
  • 15
  • your fiddle is currently empty. Besides, your ng-click is part of the same digest cycle as your change in checkbox value and is queued too early in the cycle to recognize the change. Use ng-change instead of ng-click – Angad Jan 03 '15 at 00:38
  • Yes, you are correct. – JackSparrow Jan 03 '15 at 00:44

1 Answers1

1

You need to use ng-change instead of ng-click. ng-click (Basically the click event underneath) happens too early and the change event fires only after that. Angular listens to the change event to update the model value. So listening to ng-click will be too early because angular would not have processed and set the model yet.

So try:-

   <input type="checkbox" ng-true-value='1' ng-false-value='0' 
          ng-model='product.check' ng-change="printProducts()">
         {{product.key}}{{product.check}}</label>

Demo

PSL
  • 123,204
  • 21
  • 253
  • 243