116

In Angular, I have in scope a object which returns lots of objects. Each has an ID (this is stored in a flat file so no DB, and I seem to not be able to user ng-resource)

In my controller:

$scope.fish = [
    {category:'freshwater', id:'1', name: 'trout', more:'false'},
    {category:'freshwater', id:'2', name:'bass', more:'false'}
];

In my view I have additional information about the fish hidden by default with the ng-show more, but when I click the simple show more tab, I would like to call the function showdetails(fish.fish_id). My function would look something like:

$scope.showdetails = function(fish_id) {  
    var fish = $scope.fish.get({id: fish_id});
    fish.more = true;
}

Now in the the view the more details shows up. However after searching through the documentation I can't figure out how to search that fish array.

So how do I query the array? And in console how do I call debugger so that I have the $scope object to play with?

7 Answers 7

211

You can use the existing $filter service. I updated the fiddle above http://jsfiddle.net/gbW8Z/12/

 $scope.showdetails = function(fish_id) {
     var found = $filter('filter')($scope.fish, {id: fish_id}, true);
     if (found.length) {
         $scope.selected = JSON.stringify(found[0]);
     } else {
         $scope.selected = 'Not found';
     }
 }

Angular documentation is here http://docs.angularjs.org/api/ng.filter:filter

Sign up to request clarification or add additional context in comments.

3 Comments

very helpful - As I learn angular I'm realizing that I need to stop thinking jQuery functions first (was trying to get $.grep to do this) - rather using this $filter service was just what I needed!
Could you add details what $scope.selected is / contains. Doing a quick-search on selected i found ng-selected / ngSelected: If the expression is truthy, then special attribute "selected" will be set on the element. Is this the same? In your example what does it do? Thanks
Don't forget to add the $filter service to your controller. i.e: app.controller('mainController', ['$filter', function($filter) { // $filter can now be used. }]);
95

I know if that can help you a bit.

Here is something I tried to simulate for you.

Checkout the jsFiddle ;)

http://jsfiddle.net/migontech/gbW8Z/5/

Created a filter that you also can use in 'ng-repeat'

app.filter('getById', function() {
  return function(input, id) {
    var i=0, len=input.length;
    for (; i<len; i++) {
      if (+input[i].id == +id) {
        return input[i];
      }
    }
    return null;
  }
});

Usage in controller:

app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
     $scope.fish = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}]

     $scope.showdetails = function(fish_id){
         var found = $filter('getById')($scope.fish, fish_id);
         console.log(found);
         $scope.selected = JSON.stringify(found);
     }
}]);

If there are any questions just let me know.

3 Comments

As Im new to angular and javascript, I'm not getting the meaning of '+' in "if (+input[i].id == +id) {" statement, can you please share your thoughts.
Perfect Solution !!
I think the "+input[i].id == +id" makes sure you are comparing numbers. So you can pass 1 or '1' to the $filter and it would behave the exact same way. I'm using alphanumeric Ids, so I changed it to "input[i].id === id"
22

To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:

.filter('getByProperty', function() {
    return function(propertyName, propertyValue, collection) {
        var i=0, len=collection.length;
        for (; i<len; i++) {
            if (collection[i][propertyName] == +propertyValue) {
                return collection[i];
            }
        }
        return null;
    }
});

The call to filter would then become:

var found = $filter('getByProperty')('id', fish_id, $scope.fish);

Note, I removed the unary(+) operator to allow for string-based matches...

2 Comments

considering the documentation states that this is the only use case for ng-init, I would say this is definitely the Angular way to do it.
Very easy to understand example and very helpful
13

A dirty and easy solution could look like

$scope.showdetails = function(fish_id) {
    angular.forEach($scope.fish, function(fish, key) {
        fish.more = fish.id == fish_id;
    });
};

3 Comments

Why this is a dirty solution ?
my guess would be because there may be, like, a billion fish records and we're just looping through them one by one
There'd be even more records in other languages. I mean, there's plenty of fish in the C++. (Oh shut up.. I'll go and vote myself down..!!)
7

Angularjs already has filter option to do this , https://docs.angularjs.org/api/ng/filter/filter

Comments

7

Your solutions are correct but unnecessary complicated. You can use pure javascript filter function. This is your model:

     $scope.fishes = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}];

And this is your function:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter({id : fish_id});
         return found;
     };

You can also use expression:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter(function(fish){ return fish.id === fish_id });
         return found;
     };

More about this function: LINK

Comments

4

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

1 Comment

This worked for me. Simple, slick, easy to test. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.