简体   繁体   中英

angular ng-repeat checkbox from resource and set checked

i have resource in my controller and populate checkboxes with ng-repeat next thing i know in controller which are to be checked

code will looks like..

$scope.data = resource.query();

var arr_to_be_checked = [1,3,5];

in other controller i use this..

$scope.data = [ { Type: 1, checked: true, Title: 'Item A'},
                { Type: 2, checked: false, Title: 'Item B'}];

and its working fine but i need apply this on resource and ng-repeat because i need more flexible

i find any soulution but without point. Pls can you help me anyone?

My question is: How i can "override" objects in resource with 'checked:true' or set any checkbox as checked.

Thank you so much for help or any idea
Have a nice day


<ul>
  <li ng-repeat="item in data">
    <input type="checkbox" ng-checked="item.checked"> {{item.Title}}
  </li>
</ul>
<button ng-click="checkItems()">Do</button> 

.

$scope.checkItems = function () {
  var i;
  for (i = 0; i < arr_to_be_checked.length; i++) {
    data[arr_to_be_checked[i]].checked = true;
  } 
};

PS: Please be really consistent on your naming conventions, javascript uses a camelCase naming convention, no underscores. Only constructor functions are named PascalCase

Related API Documentation:
ng-click
ng-checked

Another solution:

<div ng-controller="MainCtrl">
  <label ng-repeat="(color,enabled) in colors">
      <input type="checkbox" ng-model="colors[color]" /> {{color}} 
  </label>
  <p>colors: {{colors}}</p>

<script>
  var app = angular.module('plunker', []);

  app.controller('MainCtrl', function($scope){
      $scope.colors = {Blue: true, Orange: true};
  });

http://plnkr.co/edit/U4VD61?p=preview

SOLUTION

i look at solution from fastreload and modified like this..

var arr_checked_items = [1,2,5] // this checkboxes will be set as checked


<ul>
  <li ng-repeat="item in data">
    <input type="checkbox" ng-checked="checkItem(item.id)"> {{item.Title}}
  </li>
</ul>

.

$scope.checkItem = function (id) {
   var checked = false;
   for(var i=0; i<= arr_to_be_checked.length; i++) {
      if(id == arr_to_be_checked[i]) {
         checked = true;
      }
    }
    return checked;
};

ITS WORKING PERFECT !!! on load without any clicking buttons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM