使作为过滤器的功能

时间:2014-08-29 09:55:17

标签: javascript angularjs

我是AngularJS的新手。我试图使用作过滤器的功能:

的index.html

    <ul class="phones">
      <li ng-repeat="phone in phones | filter:isLong">
        {{phone.name}}
      </li>
    </ul>

controllers.js

phonecatApp.controller('PhoneListCtrl', function ($scope) {

  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.'}
  ];

  $scope.islong = function(phone) {
    var n = phone.name.length;
    if ( n > 7) { return true } else { return false };
  }
});

JsBin

http://jsbin.com/huwam/1/edit

但这不起作用......请帮助我。谢谢你的好意。

2 个答案:

答案 0 :(得分:3)

正如@zeroflagL所说,

&#34;您只需要引用该功能,而不是调用它:&#34;

 <li ng-repeat="phone in phones | filter:isLong">

另一种方法是创建自定义过滤器以实现此目标。

主要原因是:自定义过滤器可在任何范围内重复使用。

<强> HTML

<ul class="phones">
  <li ng-repeat="phone in phones | islong">
    {{phone.name}}
  </li>
</ul>

<强>的javascript

phonecatApp.filter("islong", function() {
    return function(items) {
       return items.filter(function(item) { return item.name.length > 7});
    };
});

http://plnkr.co/edit/F374dQ?p=preview

可能是您想要添加参数:

<强> HTML

<ul class="phones">
  <li ng-repeat="phone in phones | islong:7">
    {{phone.name}}
  </li>
</ul>

<强>的javascript

phonecatApp.filter("islong", function() {
    return function(items, length) {
       return items.filter(function(item) { return item.name.length > length});
    };
});

来源:https://docs.angularjs.org/tutorial/step_09

答案 1 :(得分:0)

您只需要引用该功能,而不是调用它:

 <li ng-repeat="phone in phones | filter:isLong">

函数本身获取一个项目作为参数:

$scope.isLong = function(phone) {