Using Angular-UI and Restangular To Interact With WordPress API

Written by Ben Wendt

At my new job I’ve been working a fair bit with ui router. It’s a fun library and I thought I would brush up a bit and have some fun practice interfacing it with the wordpress api plugin through restangular.

So let’s take a quick look at how this very simple process works.

First, I installed all the dependencies using bower.

Next, set up a simple index.html file:

<!doctype html>
<html ng-app="blog">
<head>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
    <script src="bower_components/lodash/lodash.min.js"></script>
    <script src="bower_components/restangular/dist/restangular.js"></script>
    <script src="app.js"></script>
</head>
<body>
<div>
<div ui-view></div>
</div>
</body>
</html>

And here’s app.js:

var myApp = angular.module('blog', ['ui.router', 'restangular']);
myApp.config(function($stateProvider, $urlRouterProvider, RestangularProvider) {

RestangularProvider.setBaseUrl('http://benwendt.ca/blog/wp-json/')

$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
  url: '/',
  templateUrl: 'posts.html',
  resolve: {
    posts:function(Restangular) {
      return Restangular.all('posts').getList()
     }
  },
  controller($scope, $sce, $filter, posts) {
    $scope.posts = posts
  }
})
}).filter('unsafe', function($sce) { return $sce.trustAsHtml })


The two main takeaways here are:

  1. Set up the base api url using RestangularProvider.setBaseUrl().
  2. Use ui-router’s $stateProvider to set up which template, api requests, and controller to use. Also I’m using a nifty filter I found for running <A href="http://stackoverflow.com/a/19705096/973810">$sce.trustAsHtml</a>.

And the template is super simple, but here it is:

<div ng-repeat="post in posts">
  <div class="post">
    <h1 ng-bind-html="post.title | unsafe"></h1>
    <div ng-bind-html="post.content | unsafe"></div>
  </div>
</div>

So, in conclusion, these technologies make it really easy to pull data off a json api and throw it into the browser. It’s wonderful.