how to pick up an object from an array through id with Angularjs

Asked

Viewed 4,720 times

6

I pass the id of the object coming from an ng-repeat through the $stateParams more later I would need to take the object of the array referring to the id coming from the URL to display the information. My doubt is whether I have to take this JSON object as I do ? And if there’s any other way to do that like sending the specific object instead of just the id ?

controller :

.controller('SingleController', function($scope,$http,$stateParams) {

 $stateParams.id;
    console.log($stateParams.id);

$scope.dados = Array();

    $http.get("js/dados.php").success(function(data){
        $scope.dados = data.dados;
        console.log($scope.dados);



    }).error(function(data){
        alert("Error...");
        console.log(data);
    });



});
  • 1

    Your question is very confusing. You have an array of objects and want to pick up an item through an the attribute id of this object?

  • 1

    that’s right! more also if it is possible to pass the item directly to the new page instead of passing the id and then fetching the item ...

2 answers

3

I decided as follows :

1º I created a Factory to facilitate the use of json:

app.factory('jsonExemplo', function($http) {
   return {
     getjson: function() {
        return $http.get('js/dados.php').then(function(result) {
        return result.data;
    });
  }
}
});

2º I created the list of what I wanted in the controller using Factory:

.controller('MeuController', function($scope,Exemplo ) {

jsonExemplo.getjson().then(function(data){
categorias:'1'

});

console.log($scope.dados);

});

3º Ja na Single I take the parameter and filter by ID:

app.controller('SingleController', function($scope,jsonExemplo, $stateParams,$filter, $timeout) {

    var myFilter = $filter;


jsonBaladas.getjson().then(function(data){

$scope.dados = myFilter('filter')(data.dados, {
        id:$stateParams.id

    })    
 console.log($scope.dados); 

});

});

2

Let’s go in pieces.

To find the object using the ID you can simply:

var idParaEncontrar = $stateParams.id;
var objectoEncontrado = undefined;
for(var i = 0; i < minhaColeccao.length: ++i){
    if(minhaColeccao[i].id === idParaEncontrar) {
        objectoEncontrado = minhaColeccao[id];
        break;
    }
}
if(objectoEncontrado !== undefined) {
    console.log("objecto encontrado")
}

In case you prefer to use an external library of a look at the underscore.js, more precisely in function .find().

To pass the object to the controller you can choose to use the resolve of $routeProvider.

When you open the URL that has the resolve defined, the functions are performed and the results are injected into the controller.

The benefit of this is that the functions can return promises and Angular will expect the promise to be resolved before instantiating the controller and injecting the value.

So in your case it would look something like:

resolve: {
    meuObjecto: (minhaColeccao, $stateParams) {
            // logica para encontrar o objecto, pode usar a mesma logica acima
        }]
},
  • 1

    I am unable to use the FOR inside my controller... it module error ... Uncaught Error: [$injector:modulerr] Failed to instantiate module example due to: Error: [$injector:modulerr] Failed to instantiate module inparty.controllers due to: Error: [$injector:nomod] Module 'example.controllers' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the Second argument.

  • this is a problem with your controller and not with the code itself. See if the module exemplo.controllers is being created correctly.

  • 1

    is being created yes. :/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.