Skip to content

Instantly share code, notes, and snippets.

@mohandere
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohandere/f2187b37413a16fd8d98 to your computer and use it in GitHub Desktop.
Save mohandere/f2187b37413a16fd8d98 to your computer and use it in GitHub Desktop.
Angular Factory/Service for Interaction with Wordpress Blog
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