AngularJS checkbox/复选框 根据缓存数据实时显示

时间:2022-01-10 04:59:10

想缓存选择按钮时,可以使用这样的方法。

index.html

 <!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>
<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>

ng-checked:是angular封装用来控制该checkbox是否选中使用的,return true是选中,反则不选中;

ng-click:这个是angular封装的的onclick方法,可以传入$event;

script.js


 var iApp = angular.module("App", []);

 iApp.controller('AddStyleCtrl', function($scope)
{
$scope.tagcategories = [
{
name: 'Color',
tags: [
{
id:1,
name:'color1'
},
{
id:2,
name:'color2'
},
{
id:3,
name:'color3'
},
{
id:4,
name:'color4'
},
]
},
{
name:'Cat',
tags:[
{
id:5,
name:'cat1'
},
{
id:6,
name:'cat2'
},
]
},
{
name:'Scenario',
tags:[
{
id:7,
name:'Home'
},
{
id:8,
name:'Work'
},
]
}
]; $scope.selected = []; $scope.updateSelection = function($event, id){
var checkbox = $event.target;
var action = (checkbox.checked?'add':'remove');//这里有点奇怪 相反了
if(action == 'add' && $scope.selected.indexOf(id) == -1){
$scope.selected.push(id);
}
if(action == 'remove' && $scope.selected.indexOf(id)!=-1){
var idx = $scope.selected.indexOf(id);
$scope.selected.splice(idx,1);
}
} $scope.isSelected = function(id){
return $scope.selected.indexOf(id)>=0;
}
});