Last active
August 29, 2015 14:16
-
-
Save mohandere/f2187b37413a16fd8d98 to your computer and use it in GitHub Desktop.
Angular Factory/Service for Interaction with Wordpress Blog
This file contains 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
function fzBlogFactory($http, $sce, config) { | |
function allPosts() { | |
return httpRequest('posts?filter[category_name]=post'); | |
} | |
function postByID(id) { | |
return httpRequest('posts/' + id); | |
} | |
function featuredPosts() { | |
return httpRequest('posts?filter[category_name]=post%2Bfeatured'); | |
} | |
function allPostsByTag(tag) { | |
return httpRequest('posts?filter[category_name]=post&filter[tag]=' + tag); | |
} | |
function allPostsBySearchTerm(searchTerm) { | |
return httpRequest('posts?filter[category_name]=post&filter[s]=' + searchTerm); | |
} | |
function postsByCategory() { | |
return httpRequest('posts?filter[category_name]=project'); | |
} | |
function httpRequest(url) { | |
return $http | |
.get(config.API_URL + url, { cache: true }) | |
.then(function(response) { | |
if (response.data instanceof Array) { | |
var items = response.data.map(function(item) { | |
return parseItem(item); | |
}); | |
return items; | |
} else { | |
return parseItem(response.data); | |
} | |
}); | |
} | |
/** | |
* Decorate / parse a post to make it play nice with AngularJS | |
*/ | |
function parseItem(xhrRs) { | |
xhrRs.excerpt = $sce.trustAsHtml(xhrRs.excerpt); | |
xhrRs.date = Date.parse(xhrRs.date); | |
xhrRs.content = addPermalinkToHeaders(xhrRs.content); | |
xhrRs.content = $sce.trustAsHtml(xhrRs.content); | |
return xhrRs; | |
} | |
/** | |
* Add a dirPermalink directive to any headers within the body of the post. | |
* @param content | |
* @returns {XML|string|*|void} | |
*/ | |
function addPermalinkToHeaders(content) { | |
return content.replace(/(<h[234])([^>]*>)/g, '$1 dir-permalink $2'); | |
} | |
return { | |
allPosts: allPosts, | |
post: postByID, | |
allPostsByTag: allPostsByTag, | |
allPostsBySearchTerm: allPostsBySearchTerm, | |
featuredPosts: featuredPosts, | |
postsByCategory: postsByCategory, | |
}; | |
} | |
// initiate factroy | |
angular.module('app').factory('fzBlogService', fzBlogFactory); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment