angular实时显示checkbox被选中的元素
/** * 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; } });
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <! 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 >< br > <!--根据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 > |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步