javascript - Angular : Showing only checked items in a checkbox list

标签 javascript html angularjs checkbox

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

我想做的是在选中的列表中选择一些项目,当我按下“仅显示选中的项目”时,我想在显示复选框列表中的选中项目和显示包含选中项目的整个列表。

我搜索了 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>

Working demo

关于javascript - Angular : Showing only checked items in a checkbox list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45850276/

相关文章:

iframe - iFrame 上的 Angular、onLoad 函数

javascript - 如何注入(inject) $httpParamSerializer 以在 templateUrl 中使用

javascript - 类型错误 : done is not a function

html - Firefox 中的负定位绝对元素

javascript - 如何从数组中删除每第 N 个元素

html - 为什么block会在重叠的P标签中多加一个?

html - 如何修复意外的背景溢出

javascript - ng-bind-html 在我的上下文中不起作用

javascript - React Redux 更新项数量(不止一个增量)

javascript - 覆盖移动设备上的方向转换