Skip to content

Instantly share code, notes, and snippets.

@mohandere mohandere/blogFactory.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.