user1206480
user1206480

Reputation: 1858

Unchecking a checkbox with angularjs

I have a model that renders a list of checkboxes. When I check one box I would like any other checked boxes to become unchecked. The below code seems to iterate fine, but the html is not reflecting the changes. What am I missing?

HTML:

<tr ng-repeat="x in commonOrders">
                            <td>{{x.ProductName}}</td>
                            <td>{{x.ProductItemCode}}</td>
                            <td>{{x.ProductSize}}</td>
                            <td><input type="checkbox" 
                                       ng-click="updateCommonProduct(x)" 
                                       ng-checked="x.IsChecked"/></td>
                        </tr>

angular/javascript:

$scope.updateCommonProduct = function(product) {

    // uncheck non-selected common orders
    angular.forEach($scope.commonOrders, function(value, key) {
        if (value.ProductItemCode !== product.ProductItemCode) {
            value.IsChecked = false;
        }
    }, $scope.commonOrders);



};

Upvotes: 1

Views: 8317

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32397

You should use ngModel & ngChange:

  • ngModel creates a two-way binding between the model and the DOM.
  • ngChange triggers an event when a model gets change.

Here is a plunker: http://plnkr.co/edit/lrQnA6JrvlsirqK8QGaE?p=preview

Template:

<tr ng-repeat="x in commonOrders">
   <td>{{x.ProductName}}</td>
   <td>{{x.ProductItemCode}}</td>
   <td>{{x.ProductSize}}</td>
   <td>
     <input type="checkbox" ng-change="check(x)" ng-model="x.isChecked"/>
   </td>
 </tr>

Controller method:

$scope.check = function(current) {
  angular.forEach($scope.commonOrders, function(product) {
    if(product !== current) {
      product.isChecked = false;  
    }
  });
};

Upvotes: 4

Related Questions