1
My question is how can I filter objects from an array by comparing the id
which is inside a "sub-object". Type:
animais [
{
id: 34,
nome: baleia,
categoria: {
id: 2,
nome: mamifero
},
{
id: 23,
nome: galinha,
categoria: {
id: 3,
nome: oviparo
}
}
]
Following this example, I would like to catch only mammals (id
== 2).
I have a service that returns to me all the animals:
app.factory('Animais', function($http){
var animalList,
obj = {};
obj = {
getAnimais:function(callback) {
if(animalList) {
callback(animalList);
return false;
}
else {
$http({
method: 'GET',
url: 'http://example/api/animais'
}).success(function(data) {
obj.saveAnimais:(data);
callback(data);
})
}
},
saveAnimais:function(data) {
locaisList = data;
}
}
return obj;
});
And mine controller
is as follows:
app.controller('AnimaisCtrl', function($scope, $routeParams, $filter, Animais) {
var myFilter = $filter;
Animais.getAnimais(function(data) {
$scope.animais = myFilter('filter')(data.animais, {
id:$routeParams.id
});
});
});
In the view
previous, the user selects the category. Then it is redirected to the animal screen that will show the animals of the selected category.
Somebody give me a hand?
I just wanted to filter by the category ID. Is it really necessary all this? I’m well read from Angular. :(
– Phellipe Lins
My code works, since he’s comparing the
id
ofanimais
and not of the objectcategoria
that’s inside of him.– Phellipe Lins
@Phellipelins I followed the statement in your question - 'I would like to catch only mammals (id == 2)'. I figured 'Category' was the necessary property.
– OnoSendai
As I mentioned, there are several ways. You can use a value stored in $rootScope, which can be understood as a global scope, as well as referencing values stored in a parent scope. But the recommended way is by using Services (or Factories).
– OnoSendai
It is because I am so layman that I had difficulty even to ask. Do you want me to rephrase? What would it be like? You can still help me?
– Phellipe Lins
That way I don’t understand, I need the solution in code. I have less than a week with Angularjs.
– Phellipe Lins
@Phellipelins don’t worry, we all start from scratch; it’s a pleasure to help. = ) If you can, rephrase your question without focusing on technology.
– OnoSendai
Let’s go continue this discussão in chat.
– OnoSendai