javascript - 制作充当过滤器的函数

标签 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

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

最佳答案

正如@zeroflagL所说,

“您只需要引用该函数,而不是调用它:”

 <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

关于javascript - 制作充当过滤器的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25565886/

相关文章:

javascript - 检查当前 URL 是否包含 hash

javascript - AdBlock 阻止我的网页之一

javascript - 使用解析参数注入(inject) Controller

javascript - 如何在 Canvas 底部居中放置多个 div?

angularjs - Angular/CSS - 动态添加新元素时动画移动内容

html - 如何解析 Div 类中的 Angular 作用域变量

javascript - 将数据表导出按钮移至表底部

javascript加载更多按钮不起作用

javascript - 仅识别输入中的数字标记 (JavaScript)

javascript - 带空格的正则表达式与 minify javascript 不兼容