Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to use parameters within the filter in AngularJS?

I want to use parameter in filter, when I iterate some arrays with ng-repeat

Example:

HTML-Part:

<tr ng-repeat="user in users | filter:isActive">

JavaScript-part:

$scope.isActive = function(user) {
    return user.active === "1";
};

But I want to be able to use filter like

<tr ng-repeat="user in users | filter:isStatus('4')">

But its not working. How can I do something like that?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

UPDATE: I guess I didn't really look at the documentation well enough but you can definitely use the filter filter with this syntax (see this fiddle) to filter by a property on the objects:

<tr ng-repeat="user in users | filter:{status:4}">

Here's my original answer in case it helps someone:

Using the filter filter you won't be able to pass in a parameter but there are at least two things you can do.

1) Set the data you want to filter by in a scope variable and reference that in your filter function like this fiddle.

JavaScript:

$scope.status = 1;
$scope.users = [{name: 'first user', status: 1},
                {name: 'second user', status: 2},
                {name: 'third user', status: 3}];

$scope.isStatus = function(user){
    return (user.status == $scope.status);
};

Html:

<li ng-repeat="user in users | filter:isStatus">

OR

2) Create a new filter that takes in a parameter like this fiddle.

JavaScript:

var myApp = angular.module('myApp', []);
myApp.filter('isStatus', function() {
  return function(input, status) {
    var out = [];
      for (var i = 0; i < input.length; i++){
          if(input[i].status == status)
              out.push(input[i]);
      }      
    return out;
  };
});

Html:

<li ng-repeat="user in users | isStatus:3">

Note this filter assumes there is a status property in the objects in the array which might make it less reusable but this is just an example. You can read this for more info on creating filters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...