Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I get many objects from my database which has the following structure:

$scope.user = {
    "surname" : "Kowalsky",
    "name" : "Jan",
    "subject_id" : ["123","678"]
}

I need to display all users (surnames and names) which have "123" in the subject_id array.

I tried to do it in ng-repeat but it doesn't work.

<div ng-repeat="user in userList  | filter: {user.subject_id:'123'}">
  <b>Surname: </b>{{user.surname}}
  <b>Name: </b>{{user.name}}
</div>

Also, I tried it in the controller but it also didn't work:

$scope.userFilter = $filter('filter')($scope.users.subject_id: '123')[0];
share|improve this question
    
did you try any answer? – Tarun Dugar Nov 16 at 5:47

3 Answers 3

Use a controller function in your template like this:

<div ng-repeat="user in userList  | filter: filterUser">

And declare the function 'filterUser' in your controller:

$scope.filterUser = function(item) {
   if(item.subject_id.indexOf('123') != -1}) {
       return true;
   }
   return false;
}
share|improve this answer

Try this. Remember, your variable userList is array.

app = angular.module("App", []);
app.controller("AppController", function($scope){
    $scope.userList = [
        {
            "surname" : "Kowalsky",
            "name" : "Jan",
            "subject_id" : ["123","678"]
        },{
            "surname" : "Carlos",
            "name" : "Fev",
            "subject_id" : ["344","67"]
        },{
            "surname" : "Joao",
            "name" : "Mar",
            "subject_id" : ["112","634"]
        }
    ];
}).filter('filterBySubject', function() {
    return function(userList, filter) {
        var result = [];
        
        for(var i in userList){
            if(userList[i].subject_id.indexOf(filter) > -1){
                result.push(userList[i]);
                break;
            }
        }
        return result;
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController">
<div ng-repeat="user in userList  | filterBySubject:'123'">
  <b>Surname: </b>{{user.surname}}
  <b>Name: </b>{{user.name}}
</div>
  </div>

share|improve this answer

You could utilize e.g. lodash that helps you work with collections.
Then you could prefilter your collection easily, in you controller as

$scope.users = _.filter($scope.users, function(user) {
  return _.includes(user.subject_id, '123');
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.