【问题标题】:AngularJS - Bind filter with toggle buttonAngularJS - 使用切换按钮绑定过滤器
【发布时间】:2017-11-02 21:18:58
【问题描述】:

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

当我单击每个技能时,我会为每个技能创建切换按钮,并创建过滤器,如果技能为真,则仅显示人员。两者都在工作。

如何将过滤器与切换按钮绑定?如果按钮处于活动状态,则过滤器处于活动状态。如果不是,过滤器不是。

按钮

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

【问题讨论】:

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


    【解决方案1】:

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

    <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;
    }
    

    【讨论】:

    • 非常感谢 Faly,它完全符合我的要求!能否请教您对此行的一些解释:return word ? items.filter(el =&gt; el.word) : items; 我真的很想了解代码,我不熟悉? 和el 函数
    • 它被称为“三元运算符”。如果 word 为真,则返回左侧部分(即 items.filter(el => el.word) ),如果 word 为假,则返回右侧部分(wch 是项目),因此,它相当于 if (word) { return items.filter(el => el.word) } else { return items }
    • 好吧,在快速研究了 el 和 => 之后,我想我明白了。非常感谢您的帮助!
    • 您好 Faly,很抱歉再次打扰您,但我无法使用控制器代码。仅当 $scope.word = false 时,您的解决方案才能正常工作。但是我想做一个 if 语句来初始化我的按钮的状态,例如: if (condition is true) { $scope.word = true} else { $scope.word = false } 但我有这个错误:TypeError:无法读取未定义的属性“过滤器”你能帮我吗?
    • 确保数组“组”不是未定义的,尝试记录它,...或者只需添加下面的代码以使您的过滤器返回一个空数组,以防项目(即组)未定义: if (!items) { 返回 []; } 其他 { 返回词? items.filter(...) : 项目; }
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多