2013-03-27 45 views
27

我有以下HTMLAngularjs。我如何将变量作为参数传递给自定义过滤器?

<span class="items-count">{{items | countmessage}}</span> 

而继过滤器,以显示正确的计数消息

app.filters 
    .filter('countmessage', function() { 
     return function (input) { 
      var result = input.length + ' item'; 
      if (input.length != 1) result += 's'; 
      return message; 
     } 
    }); 

但我想改用不同的词“项目(S)”,所以我修改了过滤器

app.filters 
    .filter('countmessage', function() { 
     return function (input, itemType) { 
      var result = input.length + ' ' + itemType; 
      if (input.length != 1) result += 's'; 
      return message; 
     } 
    }); 

它适用于当我使用这样的字符串时

<span class="items-count">{{items | countmessage:'car'}}</span> 

,但不从$作用域的变量的工作,是有可能使用$ scope变量

<span class="items-count">{{items | countmessage:itemtype}}</span> 

感谢

回答

35

是的,这是可以使用变量从$scope

一个例子来看看这个小提琴: http://jsfiddle.net/lopisan/Kx4Tq/

HTML:

<body ng-app="myApp"> 
    <div ng-controller="MyCtrl"> 
     <input ng-model="variable"/><br/> 
     Live output: {{variable | countmessage : type}}!<br/> 
      Output: {{1 | countmessage : type}}! 
    </div> 
</body> 

的JavaScript:

var myApp = angular.module('myApp',['myApp.filters']); 

function MyCtrl($scope) { 
    $scope.type = 'cat'; 
} 

angular.module('myApp.filters', []) 
    .filter('countmessage', function() { 
     return function (input, itemType) { 
      var result = input + ' ' + itemType; 
      if (input > 1) result += 's'; 
      return result; 
     } 
    }); 
+0

好,谢谢,我发现了,我刚刚错过了当前作用域变量,现在的工作。 – IgorCh 2013-03-27 14:21:10

+1

我们可以通过用户输入动态地生成$ scope.type吗?如:''? – Clev3r 2013-09-12 19:49:21

+0

@Clever:是的,只需将''添加到小提琴的HTML部分即可。 – lopisan 2013-09-13 09:34:07

相关问题