Created
July 28, 2014 14:11
-
-
Save ZachMoreno/c4191718036ab10df373 to your computer and use it in GitHub Desktop.
Consume JSON endpoint with Angular Service/Factory & promises
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
'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; | |
}); | |
}; | |
}]) |
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
'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; | |
}); |
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
<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