/** * Created by zh on 20/05/15. */ // Code goes here var iApp = angular.module("App", []); iApp.controller(‘AddStyleCtrl‘, function($scope) { $scope.tagcategories = [ { id: 1, name: ‘Color‘, tags: [ { id:1, name:‘color1‘ }, { id:2, name:‘color2‘ }, { id:3, name:‘color3‘ }, { id:4, name:‘color4‘ }, ] }, { id:2, name:‘Cat‘, tags:[ { id:5, name:‘cat1‘ }, { id:6, name:‘cat2‘ }, ] }, { id:3, name:‘Scenario‘, tags:[ { id:7, name:‘Home‘ }, { id:8, name:‘Work‘ }, ] } ]; //用于存储选中的值 $scope.selected = []; $scope.selectedTags = []; //更新事件 var updateSelected = function(action,id,name){ if(action == ‘add‘ && $scope.selected.indexOf(id) == -1){ $scope.selected.push(id); $scope.selectedTags.push(name); } if(action == ‘remove‘ && $scope.selected.indexOf(id)!=-1){ var idx = $scope.selected.indexOf(id); $scope.selected.splice(idx,1); $scope.selectedTags.splice(idx,1); } } //用于监控点击事件,checkbox选择了就更新 $scope.updateSelection = function($event, id){ var checkbox = $event.target; var action = (checkbox.checked?‘add‘:‘remove‘); updateSelected(action,id,checkbox.name); } //判断存储的变量中是否已包含该checkbox,$scope.selected.indexOf(id)>=0是个布尔值
$scope.isSelected = function(id){ return $scope.selected.indexOf(id)>=0; } });
<!DOCTYPE html> <html data-ng-app="App"> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> <script src="script2.js"></script> </head> <body data-ng-controller="AddStyleCtrl"> <div>Choose Tags</div> <div> <div>You have choosen:</div> <hr> <label data-ng-repeat="selectedTag in selectedTags"> (({{selectedTag}})) </label> <hr> <div data-ng-repeat="category in tagcategories"> <div>{{ category.name }}</div> <div data-ng-repeat="tag in category.tags"> <div> <!--根据ng-repeat生成一些button--> <input type="checkbox" id={{tag.id}} name="{{tag.name}}" ng-checked="isSelected(tag.id)" ng-click="updateSelection($event,tag.id)"> {{ tag.name }} </div> </div> <hr> </div> </div> <pre>{{selected|json}}</pre> <pre>{{selectedTags|json}}</pre> </body> </html>
出处: http://www.cnblogs.com/CheeseZH/
时间: 2024-10-10 21:26:07