Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

angularjs - Angular filter exactly on object key

I have a small angular app like so:

html

<body ng-app>
  <div ng-controller="Ctrl">
    <div ng-repeat="user in users | filter:1">
      <span>{{ user.username }}, {{ user.id }}</span>
    </div>
  </div>
</body>

app.js

function Ctrl($scope) {
  $scope.users = [
    {"id":1,"username":"simon",},
    {"id":8,"username":"betty",},
    {"id":14,"username":"archie",},
    {"id":3,"username":"jumbo1"},
  ]
}

output

simon, 1
archie, 14
jumbo1, 3

What I want to do is filter an exact match for filter argument AND filter on the id field ONLY.

Basically, I want the output to be:

output

simon, 1

I am using Angular 1.2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Angular 1.1.3 or newer you can use the following:

<div ng-repeat="user in users | filter:{'id':  1}:true">

{'id': 1} says to only compare with the field id. That gets you:

simon, 1
archie, 14

:true says "exact match" resulting in:

simon, 1

Here's that working: http://jsfiddle.net/AM95H/

To filter against a list of values, if you have the list in a scope variable, I'd add a custom filter to your JS file:

$scope.filterValues = [1,8];
$scope.myFilter = function(value) {
   return ($scope.filterValues.indexOf(value.id) !== -1);
};

Used like this:

<div ng-repeat="user in users |  filter: myFilter">

To filter against a parameter list we'll create our own filter. In this case we'll get called once with all the input values to test rather than once per value.

So the first parameter we'll receive is the array of input values (users in your case) and the second parameter will be the parameter we pass in ([1,8]). We'll then create an output array and add (push) any items in the input stream that match one of the filterValues. And return the output array.

myApp.filter('myFilter', function () {  
   return function(inputs,filterValues) {
      var output = [];
      angular.forEach(inputs, function (input) {
        if (filterValues.indexOf(input.id) !== -1)
            output.push(input);
       });
       return output;
   };
});

And use it like this:

<div ng-repeat="user in users |  myFilter:[1,8]">

Here's an example of this: http://jsfiddle.net/AM95H/2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...