Skip to content

Instantly share code, notes, and snippets.

@ZachMoreno
Created July 28, 2014 14:11
Show Gist options
  • Save ZachMoreno/c4191718036ab10df373 to your computer and use it in GitHub Desktop.
Save ZachMoreno/c4191718036ab10df373 to your computer and use it in GitHub Desktop.
Consume JSON endpoint with Angular Service/Factory & promises
'use strict';
/* Controllers */
angular.module('zm.controllers', [])
.controller('homeCtrl', ['$scope', function($scope) {
}])
.controller('journalCtrl', ['$scope', 'recentPostsFactory', function($scope, recentPostsFactory) {
$scope.clearData = function() {
$scope.recentPosts = {};
};
$scope.getData = function() {
// Call the async method and then do stuff with what is returned inside our own then function
recentPostsFactory.async().then(function(data) {
$scope.recentPosts = data;
});
};
}])
'use strict';
/* Services */
angular.module('zm.services', [])
.factory('recentPostsFactory', function($http) {
var promise;
var recentPostsFactory = {
async: function() {
if ( !promise ) {
// $http returns a promise, which has a then function, which also returns a promise
promise = $http.get('http://zachariahmoreno.com/api/get_recent_posts').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
return response.data;
});
}
// Return the promise to the controller
return promise;
}
};
return recentPostsFactory;
});
<button ng-click="getData()">Get recent posts</button>
<button ng-click="clearData()">Clear recent posts</button>
<ol>
<li ng-repeat="post in recentPosts.posts">
{{ post.title }}
</li>
</ol>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment