2013-03-27 12 views
27

Mam następujące HTMLAngularjs. Jak przekazać zmienną jako argument do filtru niestandardowego?

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

I po filtr, aby wyświetlić odpowiedni komunikat count

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

ale chcę używać różnych słów zamiast "Pozycja (e), więc zmodyfikowany filtr

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

działa, gdy używam takiego ciągu znaków

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

ale nie działa ze zmienną z zakresu $, jest to możliwe do wykorzystania zakresu zmiennej $

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

Thanks

Odpowiedz

35

Tak, to możliwe jest użycie zmiennej od $scope

Zobacz ten skrzypce na przykład: 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

ok dzięki, znalazłem już, po prostu brakowało moja zmienna dla bieżącego zakresu, to teraz działa. – IgorCh

+1

Czy możemy dynamicznie generować wartość $ scope.type przez dane wejściowe użytkownika? Na przykład: ''? – Clev3r

+0

@Clever: Tak, można to zrobić, po prostu dodaj '' do części HTML skrzypiec. – lopisan

Powiązane problemy