html5 - AngularJs自定义filter问题
阿神
阿神 2017-04-17 13:28:23
[HTML讨论组]

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

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

</p>

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

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

}

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

阿神
阿神

闭关修行中......

全部回复(2)
PHP中文网

根据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:

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

</p>
// 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/

PHP中文网

改成
<p class="col" ng-repeat="item in timeArray | filter: {row: r.row} : true">{{item.row}}</p>

看一下官方文档就可以https://docs.angularjs.org/api/ng/filter/filter(自备梯子)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号