how to get an object from an array through id with angularjs

5

I pass the object id that comes from a ng-repeat through $ stateParams more then I would need to get the array object for the id that comes from the URL to display the information. My question is if I have to get this JSON object like I do? And if you have any other way to do this, for example already send 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);
    });



});
    
asked by anonymous 02.03.2015 / 16:23

2 answers

2

I have decided as follows:

1st I created a factory to make json easier to use:

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

2º I created the listo 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);

});

3rd Ja in the Single get 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); 

});

});
    
20.03.2015 / 09:10
1

Let's break it down.

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")
}

If you'd rather use an external lookup library in underscore.js , more precisely in the .find() .

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

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

The benefit of this and that the functions can return promises and the Angular will wait for the promise to be resolved before instantiating the controller and inject the value.

So, for your case it would look something like:

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