To use inside the controller, you need to pass the service of $http which is being used, as follows:
App.controller('ListaCtrl', ['$scope', '$http', function($scope, $http){
$scope.id = 1;
$scope.dealer = "Teste";
$scope.stars = "5 Estrelas";
/* Seu $http */
var noticias = $http.get("http://localhost:8888/dealers")
.then(function(response) {
console.log(response);
});
}]);
It’s the same logic as the use of $scope, to be able to use the service, you need to reference it in the controller to be used.
Complementing the answer, the ideal would be for you to use this $http in a service, be it a service or factory. Of course this evades your initial question, but it is the best practice. Keep this little trick in mind:
- Controller -> O
controller need to use the data, but no matter to the controller how they will be obtained, it only matters to receive the data.
- Service -> You must provide the data for the
controller, what will be done next doesn’t matter, it just matters that he provided the data.
Example of using Factory to receive data in the controller:
/* Sua Factory */
App.factory('minhaFactory', ['$http', function($http) {
var factory = {
obterDados: _obterDados
}
function _obterDados() {
$http.get("http://localhost:8888/dealers").then(
function(response) {return response;}
);
}
return factory;
}]);
/* Seu Controller */
App.controller('ListaCtrl', ['$scope', 'minhaFactory', function($scope, minhaFactory){
$scope.id = 1;
$scope.dealer = "Teste";
$scope.stars = "5 Estrelas";
/* Seu $http */
var noticias = minhaFactory.obterDados();
}]);
I’ll test in a little while and I’ll get back to you with a Feedback.
– Diego Souza
I figured it was using Services or Factory. There’s how you post best practice ?
– Diego Souza
I just did what you posted. But it gave Allow-Control-Access-Origin error... I believe that by being on another localhost domain.
– Diego Souza
Probably, but you can solve this by passing a parameter of headers in your
.get().– celsomtrindade
I set the header, but it wasn’t like that.
– Diego Souza
Try specifying the file with
.json. Ps.: I edited the answer to add Factory– celsomtrindade
Ah... I can’t. Apigility works with friendly URL... I put /1 at the end to get only one. I will see if there is a way to do this...
– Diego Souza
Beauty, but the important thing is that the controller worked! = D Now is probably some limitation or method of use according to your desktop.
– celsomtrindade
But it was good. I understood at least your explanation. Now I need to see this Header. Thank you!
– Diego Souza
I gave a
console.log(noticias)under thevar noticiasand returned Undefined. That’s right ?– Diego Souza
Try with the use of
.then()– celsomtrindade