【问题标题】:Angular custom filtering by condition in HTML doesn't work按 HTML 中的条件进行角度自定义过滤不起作用
【发布时间】:2016-07-21 15:03:43
【问题描述】:

我的角度很新,所以我的问题可能看起来简单或愚蠢,但我没有找到任何解决方案。 我的控制器中有一个集合(例如,整数集合),我想过滤它并获取条件为真的项目。

一开始我试过这个:

<div>{{myCollection.find(item => item === 2)}}</div>

它没有工作。 然后我找到了另一种方法(我不喜欢这种方法,因为我总是只有一个元素要显示,而且不需要重复):

<div ng-repeat="item in list | filter:{item === 2}">
    <div>{{item}}</div>
</div>

而且它也不起作用。 这是我努力的 JSBin:http://jsbin.com/govovocace/1/edit?html,js,output

我的问题有什么可能的解决方案吗?在控制器中计算必填字段并将其传递给视图不适合我(不幸的是)。

【问题讨论】:

    标签: javascript angularjs angularjs-ng-repeat ng-repeat angularjs-filter


    【解决方案1】:

    你有语法错误。您不应该在过滤器中提及任何object,因为您正在直接过滤您正在循环的实际对象。最后一个选项true 是因为我们要执行精确检查。

    HTML

    <div ng-repeat="item in list | filter: 2: true">
        <div>{{item}}</div>
    </div>
    

    Demo Plunkr

    【讨论】:

    • 非常感谢!这正是我想要的!我希望我有足够的声誉来支持您的答案并将其标记为已接受:)
    • 我觉得你已经够了,谢谢 ;)
    【解决方案2】:

    您可以像这样在控制器中定义过滤器功能:

    $scope.filterFn = function(val){
        return val === 2;
    };
    

    然后像这样在你的模板中使用它:

    <div ng-repeat="item in list | filter:filterFn">
        <div>{{item}}</div>
    </div>
    

    你说,这相当于只是过滤数组开始,所以我不确定这是否满足您的需求。如果您有特定的用例,这不适合在 cmets 中告诉我。

    【讨论】:

    • 谢谢!它也有效,但 Pankaj 的答案更适合我,因为我不更换控制器。不过还是谢谢!
    【解决方案3】:

    我会做这样的事情

    .controller('SomeController',function($scope){
    
     // get the list from somewhere
      $scope.list  = [] // some array for instance
    
      $scope.dataList = list.filter(function(i){
         return i.someVal==list.someVal; // condition that satisfy your req
      });
    
    });
    

    现在在视图中使用它

    <div ng-repeat=" item in dataList"> 
       {{item}}
    </div>
    

    如果你的条件只返回一个结果,那么你可以这样做

    $scope.dataList = list.filter(function(i){
             return i.someVal==list.someVal; // condition that satisfy your req
          })[0];
    

    【讨论】:

    • 对不起,这个解决方案不适合我的情况。我在控制器的 $scope 中没有数据 - 它稍后会添加到某个地方,所以我无法在里面过滤它。我知道这听起来很奇怪,但这是真的。
    猜你喜欢
    • 2018-03-17
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2014-08-07
    • 2014-12-16
    相关资源
    最近更新 更多