html5 - AngularJs自定义filter问题

查看:173
本文介绍了html5 - AngularJs自定义filter问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<div class="row" ng-repeat = "r in rArr">

 <div class="col" >{{r.date | date:'HH:mm'}} </div> <div class="col" ng-repeat="item in timeArray | filter : func(r.row,item.row)">{{item.row}}</div>

</div>

$scope.func = function(r1,r2) {

            console.log(r1);
            console.log(r2);
            return r1 == r2;

}

问题:前端传的item是undefined的 即r2是undefined的 这是为何呢?
filter对字符串的处理是包含就返回true 我想做的是2个字符串相等才返回true。

解决方案

根据angularjs官网介绍,filter后面如果是function,传入的参数应该是:

function(value, index, array): A predicate function can be used to 
write arbitrary filters. The function is called for each element 
of the array, with the element, its index, and the entire 
array itself as arguments.

angularjs会用这个函数遍历你传入的数组,形式跟forEach中的回调函数一样,
第一个参数是每一个元素,第二个是index,即索引值,第三个是数组本身。

所以,你直接传入func即可,签名形式是固定的。另外,对于复杂对象,你还要注意比较操作是否合理,一般情况可能是浅比较,即比较的是引用值,而不是对象内容。

比如我自己实现了一个demo:

<div ng-app ng-controller="myCtrl">
  <input type="text" ng-model="selit.id">
  <br>
    <!-- 只需要传入函数名即可 -->
  <p class="row" ng-repeat="r in rows|filter:comp">{{r.label}}</p>

</div>
// app.js 
function myCtrl($scope) {
  $scope.rows = [{
    'id': 10,
    'label': 'test1'
  }, {
    'id': 27,
    'label': 'test2'
  }, {
    'id': 39,
    'label': 'test3'
  }, ];
  
  $scope.selit = {id: 10};
// angularjs 会自动调用它,并把相应的参数传过来。
  $scope.comp = function(item, index, array) {
      if (!!item) {
      // 在这里你做相应的判断逻辑
        return item.id == $scope.selit.id;
      } else {
        return true;
      }
  }
};

当然,如果你想在模板中指定比较的对象,可以这样:

  <p class="row" ng-repeat="r in rows|filter:compWith(selit)">{{r.label}}</p>
//==== app.js 
function myCtrl($scope) {
  $scope.compWith = function(comp_value) {
// 通过闭包的形式,把comp_value传入以下的回调函数中,最后还是返回一个函数对象。本例中,
// 最后的2个参数不用,可以删掉。
      return function(item/*, index, array*/) {
      if (!!item) {
        return item.id == comp_value.id;
      } else {
        return true;
      }
    }
  }
};

源代码参考:https://jsfiddle.net/flybywind/4tf73mzj/

这篇关于html5 - AngularJs自定义filter问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆