tspore tspore - 4 months ago 35
Javascript Question

In Angular, I need to search objects in an array

In Angular, I have in scope a object which returns lots of objects each has an idea (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?

Answer

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.