AngularJS - 带切换按钮的绑定过滤器

时间:2017-11-02 11:47:45

标签: angularjs angularjs-scope angularjs-ng-repeat

我有一个有真假技能的人员列表,我想用与每项技能相关的按钮来过滤数据。

当我点击它时,我为每个技能创建了切换按钮,并且我创建了过滤器,如果技能为真,则仅显示人员。两者都有效。

如何使用切换按钮绑定滤镜?如果按钮处于活动状态,则过滤激活。如果没有,则不过滤。

按钮

 <button id="word" ng-class="{'active-word': wordActive}" ng-click="wordButton()">Word</button>

 app.controller('skillsCtrl', function ($scope) {
      $scope.wordActive = false;
      $scope.wordButton = function() {
      $scope.wordActive = !$scope.wordActive;
 }

过滤

app.filter('wordskills', function () {
  return function (items) {

    var filtered = [];
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.word == true) {
        filtered.push(item);
      }
    }
    return filtered;

  };
});

查看

<div class="container" ng-repeat="person in group | wordskills">

1 个答案:

答案 0 :(得分:0)

点击后,您可以切换传递给过滤器的变量。然后,只有在此变量为真时才进行过滤:

<button ng-click="word = !word" id="word" ng-class="{'active-word': wordActive}" ng-click="wordButton()">Word</button>

<div class="container" ng-repeat="person in group | wordskills: word">

app.filter('wordskills', function () {
    return function (items, word) {
        return word ? items.filter(el => el.word) : items;
    };
});
app.controller('skillsCtrl', function ($scope) {
      $scope.word = false;
}