2015-02-24 17 views
10

mam następujący kod htmlangularjs filtr o dokładnych wartości (ścisła równość)

<ul ng-repeat="friend in friends | filter: { age: '2' } | orderBy: 'name' "> 
    <li>{{friend.name}}</li> 
    </ul> 

Oto moja $ zakres zmienny

$scope.friends = [ 
{ name: "Peter", age: 2 }, 
{ name: "Pablo", age: 55 }, 
{ name: "Linda", age: 20 }, 
{ name: "Marta", age: 37 }, 
{ name: "Othello", age: 20 }, 
{ name: "Markus", age: 32 } 
]; 

Zwraca

Linda 
Markus 
Othello 
Peter 

Jak się praca z porównaniem w filtrze ng i jak uzyskać przyjaciela, który ma tylko wiek 2 lat:

Peter 
+0

W celu dokładnego dopasowania do filtra trzeba będzie spisać niestandardową filter.Refer na to pytanie http://stackoverflow.com/questions/17480526/angularjs-filter-exact-match – Yameen

Odpowiedz

16

Jak kątowych 1,2, wystarczy dodać ścisły parametr (true) do filtra tak, że wygląda na dokładne dopasowanie i przekazać 2 jako liczbę zamiast napisu: filter:{age:2}:true

angular.module('myApp', []) 
 
.controller('myCtrl', function($scope) { 
 
    $scope.friends = [ 
 
    {name: "Peter", age: 2 }, 
 
    {name: "Pablo", age: 55}, 
 
    {name: "Linda", age: 20}, 
 
    {name: "Marta", age: 37}, 
 
    {name: "Othello", age: 20}, 
 
    {name: "Markus", age: 32} 
 
    ]; 
 
}) 
 
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<body ng-app="myApp" ng-controller="myCtrl"> 
 
    <ul ng-repeat="friend in friends | filter:{age:2}:true | orderBy: 'name' "> 
 
    <li>{{friend.name}}</li> 
 
    </ul> 
 
</body>

+0

Czy możesz spojrzeć na http://jsfiddle.net/w4L9zswo/. Próbowałem, co powiedziałeś, ale to nie działa. – squiroid

+0

Edytowałem komentarz actaully to jest w tym I w linku :-) – squiroid

+1

Dzięki i rozwiązałem to faktycznie istnieje problem z wersją, że nie będzie działać w 1.0.x, ale działa w 1.2.x :-) – squiroid

1

dyrektywa Dodany do konwersji wartości modelu do liczby workded dla mnie po ustawieniu ścisły parametr (true).

myApp.directive('convertNumber', [function() { 
    return { 
    require: 'ngModel', 
    link: function(scope, el, attr, ctrl) { 
     ctrl.$parsers.push(function(value) { 
     return parseInt(value, 10); 
     }); 

     ctrl.$formatters.push(function(value) { 
     if (value != null) { 
      return value.toString(); 
     }; 
     });  
    } 
    } 
}]);