angular实时显示checkbox被选中的元素
Posted zipon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } });
<!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>
以上是关于angular实时显示checkbox被选中的元素的主要内容,如果未能解决你的问题,请参考以下文章