I have a factory use $resource
to make HTTP
calls.
The factory code:
.factory('me', function($resource, API_URL) {
var url = API_URL + 'api/me';
return $resource(url);
})
I use it in a controller and I manage to display the data returned from factory in view like this:
.controller('AppCtrl', function($scope, me) {
$scope.data = me.get();
console.log($scope.data);
})
View code to display this data was obiously like this:
<h3>{{data.displayName}}</h3>
when I took a look at my console I found that am getting the data but I also getting $promise
and $resolved
I had a feeling that am not doing it the way it meant to be and I made sure when I tried to use the same factory in different controller like this:
.controller('newItemCtrl', function($scope, me) {
var data = me.get();
console.log(data.displayName);
})
I got undefined. My question again how it work in the first use and didn't in the second use.
$resource.get()
does not immediately return data. Instead it returns an empty reference that is updated with the data once the data is returned from the server.
Instead of directly assigning the result of the get()
to your scope variable, you should be using the success and error callbacks:
angular.module('foo').controller('AppCtrl', function($scope, me) {
me.get(function (result) {
$scope.data = result;
console.log($scope.data);
}, function (error) {
// handle error here
});
});