Angular:仅显示复选框列表中的选中项目

时间:2017-08-23 22:33:13

标签: javascript html angularjs checkbox

是否可以仅显示复选框列表中的已检查项目列表?

我想要做的是在选中列表中选择一些项目,当我按下"仅显示选中的项目"时,我想在显示所选项目之间切换在复选框列表中,显示包含已检查项目的整个列表。

我搜索了有角度的网站,但无法找到解决方案。

小提琴: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);
  };

});

1 个答案:

答案 0 :(得分:1)

在控制器中添加一个新变量:

$scope.showAll = true;

在视图中,当单击仅显示已选中按钮时,showAll的值反向:

<button ng-click="showAll = !showAll">Show only Checked</button>

要仅显示已选中的项目,请使用Array.includes方法,并检查当前角色是否在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>

Working demo