I want to learn how to retrieve data from a function that does a GET in an API and returns me the JSON. I want to retrieve the data and populate a list ... with ng-repeat
.
It's happening to come undefined and then I do not even know what to put in ng-repeat
.
Angular JS
/* Factory */
App.factory('dealerFactory', ['$http', function($http) {
var factory = {
obterDados: _obterDados
}
// Lista de Concessionárias
function _obterDados() {
$http.get("http://localhost:8888/dealers").then(
function(response){
return response.data;
}
);
}
return factory;
}]);
App.controller('ListaCtrl', ['$scope', 'dealerFactory', function($scope, dealerFactory){
$scope.dealers = [];
$scope.dealers = dealerFactory.obterDados();
}]);
HTML
<ion-content ng-controller="ListaCtrl">
<ion-list>
<ion-item ng-repeat="{{ result in dealers }}" id="{{result.id}}">
<h3>{{result.dealer}}</h3>
<h4>{{result.stars}}</h4>
</ion-item>
</ion-list>
</ion-content>
Update:
When I make the code below for debug reasons only, I get undefined. The URL is right, it's bringing the jSON. I tested LINK in the browser and also gave console.log
on the function return and brought me the data.
$scope.dealers = [];
$scope.dealers = dealerFactory.obterDados();
console.log($scope.dealers);
I think it's something related to Asynchronization. The variable has not changed yet, and return runs first ... I do not know how to solve it.