简体   繁体   English

带有参数的AngularJS自定义过滤器

[英]AngularJS Custom Filter with Argument

My custom filter should output: 我的自定义过滤器应输出:

Mark 标记

...however it's outputting: ...但是它输出:

  • M 中号
  • a 一种
  • r [R
  • k ķ

Here's my view: 这是我的看法:

  <body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="friend in friends | myFriend:currentUser">
        {{ friend }}
      </li>
    </ul>
  </body>

...and controller: ...和控制器:

var app = angular.module('plunker', []);

app.filter('myFriend', function () {
  return function (items, currentUser) {
    console.log(items);
    console.log(currentUser);
    for (var i = 0; i < items.length; i++) {
      if (items[i] === currentUser) {
        return items[i];
      }
    }

  };
});

app.controller('MainCtrl', function($scope) {
  $scope.currentUser = 'Mark';
  $scope.friends = ['Andrew', 'Will', 'Mark', 'Alice', 'Todd'];
});

Here is my Plunker: http://plnkr.co/edit/JCKAt05MPlrvIZBCGO0n?p=preview 这是我的Plunker: http ://plnkr.co/edit/JCKAt05MPlrvIZBCGO0n?p=preview

How can my custom filter output "Mark"? 我的自定义过滤器如何输出“标记”?

That is because you are passing a string from the filter instead of array of string. 那是因为您要从过滤器传递一个字符串,而不是字符串数组。 ng-repeat will iterate though the characters (string is an array of chars) of the string Mark and display it. ng-repeat将遍历字符串Mark的字符(字符串是一个字符数组)并显示它。 You need to instead pass array to ng-repeat . 您需要改为将数组传递给ng-repeat Filter is run first before applying source to ng-repeat . 在将source应用于ng-repeat之前,首先运行Filter。 Example: 例:

for (var i = 0; i < items.length; i++) {
  if (items[i] === currentUser) {
    return [items[i]];
  }
}

In your specific case you could just as well do as below, without creating any custom filter: 在您的特定情况下,您可以执行以下操作,而无需创建任何自定义过滤器:

 <li ng-repeat="friend in friends | filter:currentUser:true">
  {{ friend }}
</li>

As I presume you are aware the filter is being applied to the list friends. 我想您知道过滤器已应用于列表好友。

Your filter is returning a single string value. 您的过滤器返回一个字符串值。

Your ng-repeat can be thought of as: 您的ng-repeat可以认为是:

ng-repeat="friend in (friends | myFriend:currentUser)"

which means you are trying to loop over the string returned by your myFriend filter. 这意味着您试图遍历myFriend过滤器返回的字符串。 For the browser you're using ng-repeat over a string loops over each character in the string. 对于浏览器,您在字符串上使用ng-repeat会遍历字符串中的每个字符。

(Note: this might not happen on every browser, because some browsers (eg IE7) do not allow [] subscripting on strings . (Underneath it all, ng-repeat would rely on the value having a length property and [] subscripting.) (注意:这可能不会在每种浏览器上都发生,因为某些浏览器(例如IE7) 不允许在字符串上使用[]下标 。(在所有这些下面,ng-repeat都依赖于具有length属性和[]下标的值。)

The following may produce the result you want (assuming you only ever want one name to be shown from the list) 以下内容可能会产生所需的结果(假设您只希望从列表中显示一个名称)

  <body ng-controller="MainCtrl">
    <ul>
      <li>
        {{ friends | myFriend:currentUser }}
      </li>
    </ul>
  </body>

My strong suggestion is dont write extra code. 我的强烈建议是不要编写额外的代码。 Its like reinventing the wheel. 就像重新发明轮子一样。 Instead stick to the general procedure and filter it out. 相反,请遵循一般步骤并将其过滤掉。 A small change in your friends array will get you better result with minimal coding. 在friends数组中进行很小的更改将以最少的编码获得更好的结果。 Use angular to minimalize your coding. 使用角度最小化您的编码。

    <!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="friend in friends | filter:{name:currentUser}">
        {{ friend.name }}
      </li>
    </ul>
  </body>

</html>

app.js app.js

app.controller('MainCtrl', function($scope) {
  $scope.currentUser = 'Mark';
  $scope.friends = [{'name':'Andrew'}, {'name':'Will'}, {'name':'Mark'}, {'name':'Alice'}, {'name':'Todd'}];
});

Try below updated filter. 请尝试以下更新的过滤器。 You are returning String whereas you should return an array. 您正在返回String,而您应该返回一个数组。 Thats why ng-repeat is considering that String as an array and iterating every letters. 这就是为什么ng-repeat将String视为数组并迭代每个字母的原因。

app.filter('myFriend', function () {
    return function (items, currentUser) {
        console.log(items);
        console.log(currentUser);
        var finalItems = [];
        for (var i = 0; i < items.length; i++) {
            if (items[i] === currentUser) {
                finalItems.push(items[i]);
            }
        }
        return finalItems;
    };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM