AngularJS checkbox/复选框 根据缓存数据实时显示
想缓存选择按钮时,可以使用这样的方法。
index.html
1 <!DOCTYPE html> 2 <html data-ng-app="App"> 3 <head> 4 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> 5 <script src="script2.js"></script> 6 </head> 7 <body data-ng-controller="AddStyleCtrl"> 8 9 <div>Choose Tags</div> 10 <div> 11 <div>You have choosen:</div> 12 <hr> 13 <label data-ng-repeat="selectedTag in selectedTags"> 14 (({{selectedTag}})) 15 </label> 16 <hr> 17 <div data-ng-repeat="category in tagcategories"> 18 <div>{{ category.name }}</div> 19 <div data-ng-repeat="tag in category.tags"> 20 <div> 21 <input type="checkbox" id={{tag.id}} name="{{tag.name}}" ng-checked="isSelected(tag.id)" ng-click="updateSelection($event,tag.id)"> 22 {{ tag.name }} 23 </div> 24 </div> 25 <hr> 26 </div> 27 </div> 28 29 <pre>{{selected|json}}</pre> 30 <pre>{{selectedTags|json}}</pre> 31 32 </body> 33 </html>
ng-checked:是angular封装用来控制该checkbox是否选中使用的,return true是选中,反则不选中;
ng-click:这个是angular封装的的onclick方法,可以传入$event;
script.js
1
2
3 4 5 6 var iApp = angular.module("App", []); 7 8 9 10 iApp.controller('AddStyleCtrl', function($scope) 11 { 12 $scope.tagcategories = [ 13 { 14 name: 'Color', 15 tags: [ 16 { 17 id:1, 18 name:'color1' 19 }, 20 { 21 id:2, 22 name:'color2' 23 }, 24 { 25 id:3, 26 name:'color3' 27 }, 28 { 29 id:4, 30 name:'color4' 31 }, 32 ] 33 }, 34 { 35 name:'Cat', 36 tags:[ 37 { 38 id:5, 39 name:'cat1' 40 }, 41 { 42 id:6, 43 name:'cat2' 44 }, 45 ] 46 }, 47 { 48 name:'Scenario', 49 tags:[ 50 { 51 id:7, 52 name:'Home' 53 }, 54 { 55 id:8, 56 name:'Work' 57 }, 58 ] 59 } 60 ]; 61 62 $scope.selected = []; 63 64 65 66 $scope.updateSelection = function($event, id){ 67 var checkbox = $event.target; 68 var action = (checkbox.checked?'add':'remove');//这里有点奇怪 相反了 69 if(action == 'add' && $scope.selected.indexOf(id) == -1){ 70 $scope.selected.push(id); 71 } 72 if(action == 'remove' && $scope.selected.indexOf(id)!=-1){ 73 var idx = $scope.selected.indexOf(id); 74 $scope.selected.splice(idx,1); 75 } 76 } 77 78 $scope.isSelected = function(id){ 79 return $scope.selected.indexOf(id)>=0; 80 } 81 });