是否可以在复选框列表中仅显示选中项目的列表?
我想做的是在选中的列表中选择一些项目,当我按下“仅显示选中的项目”时,我想在显示仅复选框列表中的选中项目和显示包含选中项目的整个列表。
我搜索了 Angular 的网站,但找不到解决方案。
fiddle :http://jsfiddle.net/fjoLy5sq/422/
<div ng-controller="DemoCtrl">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role.id"> {{role.text}}
</label>
<br>
<button ng-click="checkAll()">check all</button>
<button ng-click="uncheckAll()">uncheck all</button>
<button ng-click="checkFirst()">check first</button>
<button ng-click="checkFirst()">Show only Checked</button>
<br><br>
user.roles {{ user.roles | json }}
</div>
Javascript:
angular.module("DemoApp", ["checklist-model"])
.controller('DemoCtrl', function($scope) {
$scope.roles = [
{id: 1, text: 'guest'},
{id: 2, text: 'user'},
{id: 3, text: 'customer'},
{id: 4, text: 'admin'}
];
$scope.user = {
roles: [2, 4]
};
$scope.checkAll = function() {
$scope.user.roles = $scope.roles.map(function(item) { return item.id; });
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push(1);
};
});
最佳答案
在 Controller 中添加一个新变量:
$scope.showAll = true;
在 View 中,当 Show only Checked 按钮被点击时反转 showAll
的值:
<button ng-click="showAll = !showAll">Show only Checked</button>
要仅显示选中的项目,请使用 Array.includes
方法,并检查当前 Angular 色是否在 user.roles
中:
<label ng-repeat="role in roles" ng-if="user.roles.includes(role.id)">
<input type="checkbox" checklist-model="user.roles" checklist-value="role.id"> {{role.text}}
</label>
关于javascript - Angular : Showing only checked items in a checkbox list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45850276/