ruud
ruud

Reputation: 210

Make checked input checkbox under condition

I would like to set some items in list as checked, but under some condition.

<div data-ng-repeat="item in items>
     <input type="checkbox" checked==item.selected> {{item.name}}
</div>

Let's imagine that I have some fileld an array named items where every single item in it has defined property selected. Depending on value of it input checkbox should be checked or not.

Upvotes: 0

Views: 1015

Answers (2)

Rayon
Rayon

Reputation: 36609

Try this:

You can put your logic of conditions in ng-init as mentioned in example below:

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.items = [{
      name: 'A'
    }, {
      name: 'B'
    }, {
      name: 'C'
    }];
    $scope.youCondition = function(item) {
      //Your logic
      if (item.name === 'A' || item.name === 'C') {
        item.selected = false;
      }
      else
      {
        item.selected = true;
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
  <meta charset="UTF-8">
  <title></title>
</head>

<body ng-controller="myController">
  <div data-ng-repeat="item in items">
    <input type="checkbox" ng-init="youCondition(item)" ng-model="item.selected">{{item.name}}
  </div>
</body>

</html>

Upvotes: 0

Vipul Agarwal
Vipul Agarwal

Reputation: 1611

Try the below code:

<div data-ng-repeat="item in items>
     <input type="checkbox" ng-model="item.selected"> {{item.name}}
</div>

Hope this helps.

Upvotes: 1

Related Questions