Just starting out with Angular and I might be approaching promises incorrectly. I have a factory that returns a promise:
.factory('myData', ['$http', '$q', function($http, $q) {
var deferred = $q.defer();
$http.get('/path/to/endpoint')
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err.what())
});
return deferred.promise;
}])
When I inject my factory somewhere, I can utilize the promise like this:
.controller('myController', ['$scope', 'myData', function($scope, myData) {
myData.then(function(result) {
$scope.data = result;
});
}]);
While this works fine, I find myself using myData
in multiple places and do not want to repeat writing a new .then
method in every directive and controller where I use the data. Once the promise is resolved, I no longer need it. Is there a way for myData
to return the unresolved promise, but automatically provide the result once it's resolved?
In simpler terms, can myData
just be the resolved result
after resolution, or must I include a new .then
each time?