Skip to content

Instantly share code, notes, and snippets.

@bfillmer
Created August 28, 2014 15:32
Show Gist options
  • Save bfillmer/70307bf442d46698cca3 to your computer and use it in GitHub Desktop.
Save bfillmer/70307bf442d46698cca3 to your computer and use it in GitHub Desktop.
Angular JS WordPress Factory
/**
* Small factory for accessing WP backend AJAX. Best used with the built in admin-ajax.php
* calls.
*
* Controller example:
var myApp = angular.module('myApp', [ 'WP' ]);
myApp.controller('myCtrl', function($scope, WPAjax){
WPAjax.setUrl(ajaxSettings.url);
WPAjax.setData({ nonce: ajaxSettings.nonce });
WPAjax.getData('wordpress_action', {}).success(function(data){
$scope.myData = data;
});
});
*/
(function(){
// Provider to access WP data.
angular.module('WP',[ ]).factory('WPAjax', function($http){
var service = {
backendUrl: '',
ajaxData: {
action: '',
nonce: '',
},
setUrl: function(url) {
service.backendUrl = url || service.backendUrl;
},
setData: function(data) {
service.ajaxData = data || service.ajaxData;
},
getData: function(action, post){
post.action = action;
angular.extend(post, service.ajaxData);
return service.performRequest(post);
},
performRequest: function(ajaxData){
return $http({
method: 'POST',
url: service.backendUrl,
transformRequest: function(obj){
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: ajaxData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
},
};
return service;
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment