Last active
August 29, 2015 14:08
-
-
Save MeirKriheli/3b1c998951504957e8d6 to your computer and use it in GitHub Desktop.
Using promises with angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('example') | |
.factory('Users', function($q, $http) { | |
var users = null; | |
return { | |
get: function() { | |
deferred = $q.defer(); | |
if (users) { | |
deferred.resolve(users); | |
} | |
else { | |
$http.get('/api/users/').then( | |
function(res) { | |
users = res.data; | |
deferred.resolve(users) | |
}, | |
function(err) { | |
deferred.resolve(err); | |
} | |
) | |
} | |
return deferred.promise; | |
} | |
}; | |
}). | |
controller('exampleCtrl', function($scope, Users) { | |
Users.get().then(function(users) { | |
$scope.users = users; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment