Using AngularJS and JSON API in Your WordPress Theme

This post is based on a tutorial video from WordPress.tv – Eric Wolfe: Building a WordPress Theme Using AngularJS.

This is the first post of a series about building WordPress themes with AngularJS and WP REST API (WP API).

AngularJS Logo

I tried AngularJs a while ago on Code School (free online course) and found it very impressive. Since my work is mostly based on WordPress in these days, learning how to make AngularJS and JSON API play nicely together, become my new hobby in the weekend.

When starting learn something new, I always start from Google. By just googling some keywords or phrases, I’ll get the most comprehensive resources on the topic I’m ready to dive in. To dig out really high quality stuff, I’ll use long tail keywords to narrow down the results. Luckily in this case, when googling “WordPress JSON API+AngularJS” there are no overwhelming results for me to sort out. I could learn on my own pace and share some tricks here to help newcomers.

Before we get started, if you’d like to know why AngularJS are popular these days, and why WordPress is good to serve as backend for websites, you could check this slide shared by Eric W. Greene, for the time of this writing, it takes the second spot when I google for “WordPress JSON API+AngularJS”.

Even if you have no experience in AngularJS, as long as you’re comfortable with coding, now you can open your favorite code editor and work with me.

0. Getting Started

If you have 30 minutes free, I’ll suggest you to watch the original video from WordPress.tv. Eric did good job in this session, and I add some new flavors that:

  1. Enqueue the scripts in theme in the WordPress way.
  2. Use the JSON REST API (official WP API), not JSON API (an old friend came before WP API).
  3. Keep the story short and focus on AngularJS and JSON API.

1. Creating a new theme

Creating a new theme for this demo. In the beginning you’ll just need 2 files in your theme: index.php and style.css. Be sure you’ve put the right comments in the style.css, or the theme will not work.

And paste some basic HTML, like this one, in the index.php.

Go to the WP admin and activate this theme.

2. Download AngularJS

You’ll have to download a copy of AngularJS to your theme folder. In the video Eric used bower to install AngularJS, you can also grab it from the official website. With bower, cd to your theme folder then type bower install angular in the Terminal, or if you prefer npm, you can do: npm install angular.

This introduction will focus on the magic of easily developing a Single Page Application with AngularJS, so we also need to download AngularJS Route by bower install angular-route or npm install angular-route.

If you use bower, the AngularJS files will be downloaded to the bower_components folder automatically.

3. Enqueue the scripts

Creating the functions.php in your theme, we’ll add an action function to hook.

And please remember to add wp_head(); to the head tag, in this way the AngularJS scripts will be inserted in the head tag.

4. Hello, AngularJS!

Let’s do some test to make sure the AngularJS is working and see some magic.

  • Line 2: the ng-app attribute added to html tag, is the way to make AngularJS work on this page.
  • Line 18: add a simple text input with the ng-model="name" attribute.
  • Line 20: and now we can access the value of the input in real-time by using {{name}}. The double curly brace notation {{ }} is a built-in Angular markup.

The homepage is done if you can get the value from the text input, see the image below. AngularJS_Demo_Theme from Using AngularJS and JSON API in your WordPress theme

5. And Hello, AngularJS Route!

Now let’s make AngularJS Route work. It would be kind of complicated so please do it with me step by step. First, we need to modify the index.php by adding some tags:

  1. Line 2: add the attribute value, now it’s like ng-app="app", you can change “app” to any string, as long as you remember to use the right app name later in your javascript.
  2. Line 4: I added this because in my case, there’s a “nobase” error in console. According to the AngularJS documentation, the base tag is to the rescue. Please note the “/jsonapi/” is the sub-context in my case (my test url is like “http://localhost/jsonapi/”), you should replace it accordingly. If you set the wrong base href, you’ll get an error like this or this. (2015/04/19 updated: Since release 0.8.1, I changed the base href to a dynamic string that will be your root directory. You should be free from setting the href manually.)
  3. Line 17: add the ng-view attribute so later the content will display in this div.

Second, create a new folder in the theme folder called “partials“, and add a new file called “main.html” in it. Write something like “This is the main file” in the html file. The folder, file name, file content can be anything you want.

Third, update the functions.php, we enqueue our scripts.js, and use wp_localized_script to make the URL of the partials folder available to scripts.js.

Fourth, it’s time to write some JavaScript. If you’ve changed the app or file name, please change them in the scripts.js accordingly.

The screen will look like this if you get all four steps right:

Screenshot 1 from Using AngularJS and JSON API in your WordPress theme

6. JSON REST API plugin

All the 5 steps above let us realize the magic power in AngularJS, now we’ll get JSON REST API to work. Please install JSON REST API (WP API) and activate it. Also you need to enable the permalink to make it work.

With JSON REST API, you can get the latest WordPress posts in JSON format with URL like this:

[SITE_URL]wp-json/posts

And the screen will look like this:

Screenshot from Using AngularJS and JSON API in your WordPress theme

7. Display WordPress posts with AngularJS and JSON API

Now we’d like to use AngularJS to get the latest posts, and display them on the homepage. In our scripts.js, we tell AngularJS to go get the “wp-json/posts/”, and pass the result to an object called posts when success.

And we need to change the markup in main.html to display the loop. See the elegant ng-repeat below, I really like this one. (If you prefer to user slug, please check out the following post: Using Slug To Get Single Post In AngularJS WordPress Theme)

Note you can use the keys in the JSON to display values like {{post.ID}}. Now we get the loop on our homepage.

Screenshot from Using AngularJS and JSON API in your WordPress theme

8. Display a single WordPress post with AngularJS and JSON API

Add another file to your partials folders called content.html:

Update the scripts.js to:

  1. Line 10: be careful there’s a “:” before ID. In such syntax, it means a route parameter, not a string called “ID”.
  2. Line 25: We tell AngularJS to get “wp-json/posts/[ID Param]”, and JSON API would give us the single post.

So now you can get the single post view without refresh the whole page. That’s what makes a Single Page Application.

Screenshot from Using AngularJS and JSON API in your WordPress theme


Thank you for spending time with me and this tutorial. I hope you enjoy it and can’t wait to learn more about AngularJS and JSON API like me. There’s another tutorial for beginners by Alisa Ryan Herr is worth a read. And Josh Pollock is going to write a 3-part series about WordPress and Single Page Application on Torque Mag, though he’ll use node.js on the front-end.

You can download the final theme from this GitHub Repo. I’d love to hear from you and discuss any coding issues if you bump into with the steps above. Talk to you soon.

P.S. If you feel confused about the last screenshot, you can find the solution in the next post: AngularJS WordPress Theme: Display Post Content with ngBindHtml.

228 responses

  1. Hey,

    great writeup! Im trying to use your tips to pull information from a wordpress blog (blog.domain.com) into landing page made with angularjs (domain.com). if I follow your tutorial something goes wrong since angluar is not inside wordpress and i get “Access-Control-Allow-Origin” error and i guess there are other things i have to change

    1. Yoren Chang Avatar
      Yoren Chang

      Jerry,

      Thank you for sending feedback to me. Let me do some research to find the possible solutions. I’ll get back to you as soon as I can.

    2. Yoren Chang Avatar
      Yoren Chang

      Jerry, I just found Josh had provided the solution to the issue you encountered. Please refer to his article: http://torquemag.io/preparing-wordpress-site-power-single-page-web-app/.

      Please try and let me know if it works. Thanks!

  2. […] I wrote a tutorial on AngularJS and JSON API, I’d really like to share what I learnt with newcomers. Somehow I recalled once I’ve […]

  3. […] the last screenshot of my previous post Using AngularJS And JSON API In Your WordPress Theme, you might be wondering why the post content displayed with the HTML tag, which looks like […]

  4. Thanks, I have been trying to get AngularJS and WP-API working and your tutorial finally helped me make that happen. One thing I am curious about is how to make it so that every request (even just “[SITE_URL]wp-json/posts”) requires authentication, I am workign on something and want to make sure that posts are not accessible by everyone.
    Thanks Again!
    ajt

    1. Yoren Chang Avatar
      Yoren Chang

      hi, Andrew,

      For the Cross origin issues, other sites (from different domains) can’t fetch our posts with JS through REST API. We don’t need extra authentication to implement this. For more information, like how to set allowed domains to communicate with WP REST API, you can check this post: http://torquemag.io/preparing-wordpress-site-power-single-page-web-app/

      Good to know this post help. 🙂

      1. Yoren Chang Avatar
        Yoren Chang

        And if you’re looking for a solution to prevent server side scripts to request the WP REST API, I agree with the thread on stackoverflow: http://stackoverflow.com/questions/856045/how-to-restrict-json-access, that APIs are public, we can’t restrict the access, just make it much harder.

        1. Thanks for the reply and the links, I will be working with sensitive data and want to make sure that the api is atleast as restricitve as google or facebook api.

          1. Yoren Chang Avatar
            Yoren Chang

            I think WordPress assumes blogs are public, so the WP API doesn’t provide authentication mechanism on getting posts (for now).

            In my opinion, WordPress isn’t a very good choice to store sensitive data, cause data will be plain text in the database…(except user passwords)

      2. Thanks again for the links and help, I am a novice at OOP, but I was wondering if there was a way to extend the class of the WP-API plugin so that only when someone is logged in the plugin and links will work, otherwise they will get redirected.

        1. Yoren Chang Avatar
          Yoren Chang

          Hey, Andrew,

          If we call the API from a theme or plugin (not call it externally), I believe we can do so (check if the user has logged in). I’ll do some tests and let you know the results.

        2. Yoren Chang Avatar
          Yoren Chang

          I just did the test and I’m sure that we can use `pre_get_posts` action to prevent the posts from being queried. Add this to your `functions.php`: https://gist.github.com/yoren/e56f6963cc2a40f92eb9

          It will intercept posts in a theme or a plugin, even when you get posts from WP API. I’m not sure if this is the best practice, but it should work.

  5. […] previous posts (1st, 2nd, 3rd) I’ve covered several topics in AngularJS with a very simple WordPress theme, […]

  6. Very useful tutorial thank you for your time making this.

    1. Yoren Chang Avatar
      Yoren Chang

      Tim, thanks for your kind words. It’s my pleasure to introduce AngularJS to more WP developers.

  7. Thanks Yoren! I share your love for AngularJS and as I’m also a WordPress developer the potential is just SOOO exciting! Can’t wait to start build Angular-WordPress sites!!

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Ryan, glad you like the tutorials I wrote. And thanks for the sharing!

  8. Hello Yoren,

    I can’t seem to make this work using your method. I thin I have followed all the steps as you mentioned and I even tried downloading your demo and just installing and configuring that. I keep getting an error in my console that says:
    Error: [$rootScope:infdig] http://errors.angularjs.org/1.3.2/$rootScope/infdig?p0=10&p1=%5B%5D

    I’m not sure why. Can’t make much sense of it.
    I am running my WordPress install on MAMP, I didn’t install any angular files using bower, I just added them in my directory. Can it still work like this? I don’t understand why I have to use bower. I got it working with another tutorial but that one doesn’t separate the templates into another folder and uses a somewhat outdated method, i.e they didn’t use ngRoute so I’m guessing it must quite old information.

    Thanks

    1. Yoren Chang Avatar
      Yoren Chang

      hey Ryan, I did some tests and found you might set the wrong base href in step 5. Just email you some instructions. Hope that helps.

      1. Mangesh Avatar

        Hi YOREN CHANG, Could u please send me that same email..because i am facing the same issue right now….Thanks in advance

      2. Hello YOREN CHANG i’m so happy i found this article however, i’m having the same issue. could you send me that email as well.

  9. Great tutorial 🙂 thanks for making it.

    But do you know how to get the to browser somehow render the script tags that come with the json content? I see you also have tags on your json content return.

    Been trying to find a way and nothing yet that doesn’t completely strip all the formatting.

    Thanks once a agin,

    1. Yoren Chang Avatar
      Yoren Chang

      hey Page, just check my second post in this series: https://1fix.io/blog/2014/11/13/angularjs-wordpress-theme-ngbindhtml/

      I believe it would solve the tag issue. If it’s not what you asked for, just let me know. Thanks!

  10. As an alternative you could use https://wordpress.org/plugins/json-rest-api/ plugin and https://www.npmjs.com/package/wp-api-angularjs to directly request you wordpress API with AngularJs.
    Cheers

    1. Yoren Chang Avatar
      Yoren Chang

      hey Shprink, thanks for the info, I used the json-rest-api in my article, not the json api. (sorry the title is not clear enough) I haven’t tried “wp-api-angularjs” yet, it looks like an interesting project. 🙂

  11. These tutorials are great. I’m a newbie to this and wanted to add a featured image to the ‘Main’ list. After following your steps to add Angular-Sanitize in your second post, I simply added below {{post.title}}.

    Now I’m curious about using wp-json/media, and how to, for example, get a specific uploaded video or image to place as a banner. Sorry if this is a bit beyond the scope of this specific tutorial.

    I’m looking forward to reading more of your tutorials.

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Stuart, thanks for your feedback. The topics you suggested will be included into this series later as planned. So stay tuned! 🙂

    2. Ed Barahona Avatar
      Ed Barahona

      Here is the HTML markup for the featured image of the post, assuming that you set a featured image.

      1. Ed Barahona Avatar
        Ed Barahona

        img ng-src=”{{ post.featured_image.source }}” alt=”{{ post.title }}”/

  12. Thanks for the great tutorial,
    But i got some error like this : TypeError: Cannot read property ‘replace’ of undefined.
    Is there any explanation of this? thanks

    1. Yoren Chang Avatar
      Yoren Chang

      hey Mifta,

      hmm… Can you send me a copy of your code (zip the theme folder)? Email to yoren [at] 1fix.io

      1. Hi Yoren, Finnally I have fixed it myself. I downloaded from your github repo and the problem is in the script.js on line 3. ‘app.config([‘$routeProvider’, ‘$locationProvider’, function($routeProvider, $locationProvider) {‘
        with this one :
        app.config(function($routeProvider, $locationProvider) {

        and comment out the $locationProvider.html5Mode(true);

        Anyway, thanks for your reply.

        1. Yoren Chang Avatar
          Yoren Chang

          oh, have you check the “base href” setting in your index.php? If you’ll need to comment out “$locationProvider.html5Mode(true);” to make your app work, there might be something wrong with the “base href”.

          1. i added something like this to make it work:
            <base href="/”>
            note that without the last / after the php string it didnt work…

          2. wp remove the php from my comment 🙂

  13. That’s it 🙂 I change “base href” and it works.
    Thank you.

    1. Yoren Chang Avatar
      Yoren Chang

      Good to know that. Happy learning AngularJS with WordPress!

    2. Dave Lindberg Avatar
      Dave Lindberg

      I ran into the same issue. Changing the base href to “/” made everything happy. Found good background here: https://docs.angularjs.org/error/$location/nobase

      BTW, thanks Yoren for posting this tut. Really helpful!

      1. Yoren Chang Avatar
        Yoren Chang

        Hi, Dave, Glad I could help. Happy learning AngularJS and keep me posted if you have any tips to share. 🙂

      2. I ran into the same problem. html5Mode created an error and my page kept loading the main.html no mater what I clicked. replacing the base by ‘/’ sorted all out.

        Thank you very much for this tutorial and for the comment as well 🙂

        1. Yoren Chang Avatar
          Yoren Chang

          Hey Adrien,

          The base href confuses lots of beginners so since 0.8.1 (https://github.com/1fixdotio/angularjs-demo-theme/commit/7cb732d85a8e54c76268f9eaaafed729e6a390e0) I replaced the value with a dynamic string.

          For most people who install their site at the root of the domain, “/” would work great.

          Cheers!

  14. I’m getting JS errors (running self-hosted):

    “Error: undefined is not an object (evaluating ‘b.replace’)”

    1. (that’s using your github master with no changes, too)

    2. Yoren Chang Avatar
      Yoren Chang

      Please refer to the comments above, and my theme won’t work on your server without changing the base href in the index.php

      1. I had to turn off html5mode() and remove the base ref for it to work.

        Before I discovered that, I also uploaded your github repo to a fresh install on Dreamhost, where it also failed to work.

      2. (I’m an idiot; changed my base to the proper path now. Apologies)

        1. Yoren Chang Avatar
          Yoren Chang

          hey Chris, Glad it finally works for you 😉

  15. Ekaterina Avatar
    Ekaterina

    Hi, Yoren!
    I’m getting the same with both your example and WordPress Angular plugin — routes don’t work and I can’t see subtemplates (like “main.html”). I changed base href, maybe you can assume at least what can I check to understand what’s happening.
    Thank you!

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Ekaterina, I haven’t tested my theme with WordPress Angular plugin, so I’m not sure what’s going on here. I believe you can check out Roy’s website and he’ll guide you how to integrate the plugin with themes.

      1. Ekaterina Avatar
        Ekaterina

        No, I mean I tried your code without plugin and also plugin with another theme and I see the same problem

        1. Yoren Chang Avatar
          Yoren Chang

          Can you send me a copy a your theme? Have no idea about your problem.

  16. Thanks for the great tutorial – I’m having a problem when I get to adding the routes. Where does the scripts.js file go? I get the following error when I add =”app” to ng-app:
    Uncaught Error: [$injector:modulerr]

    Thanks, Bob

    1. Sorry – I just forgot to enqueue it . . .

      1. Yoren Chang Avatar
        Yoren Chang

        Hi, Bob, glad you figured it out. Let me know if you need my assistance.

  17. Thanks Yoren, I actually ran into another problem you might be able to steer me in the right direction.

    I’ve got everything working as per your tutorial – now I’m trying to add Bootstrap. I’ve added the wp_enqueue_script the same way as adding the Angular scripts, but I can only get Bootstrap to work on the index page and I want to be able to add it to WP pages and posts – any suggestions?

    1. Yoren Chang Avatar
      Yoren Chang

      Hi Bob, can you send me a copy of your theme? To sort things out, looking into the code would be a better approach.

  18. […] WordPress sites with AngularJS and the RESTful plugin JSON API @ DevLink 2014 (source code on git) Using AngularJS And JSON API In Your WordPress Theme AngularJS front-end with WordPress back-end Using AngularJS with a WordPress backend […]

  19. […] If you’re new here, I’ll recommend that you start from the first post in this series: Using AngularJS and JSON API in Your WordPress Theme, which is listed on the Resources page at wp-api.org. It will definitely help you to build a quick […]

  20. I am getting below error.
    TypeError: Cannot read property ‘replace’ of undefined
    at Fb (angular.js:10611)
    at Me.$get (angular.js:11421)
    at Object.e [as invoke] (angular.js:4203)
    at angular.js:4021
    at d (angular.js:4162)
    at Object.e [as invoke] (angular.js:4194)
    at angular.js:4021
    at d (angular.js:4162)
    at Object.e [as invoke] (angular.js:4194)
    at angular.js:6524

    1. Yoren Chang Avatar
      Yoren Chang

      Hey, please refer to the previous comment https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/#comment-6562, change the base href should do the trick for you.

      1. Hi Yoren,

        That problem was fixed and here is a link: http://kutec.co.in/test. But I have created 4 posts and it is showing only first two posts.

        I also verified with JSON data and it has all posts that I have published: http://kutec.co.in/test/wp-json/posts/

        Can you tel me why I am not getting all posts.

        1. Yoren Chang Avatar
          Yoren Chang

          Hey Kushal, I’m out of town till Friday for a short trip. Will get back to you ASAP. Cheers.

        2. Hi I have fixed this. Actually I was testing with some proxies where publishing to public was disabled. The code is actually working well at no restriction zone.

          Thanks for quick response.

          1. Yoren Chang Avatar
            Yoren Chang

            I’m glad you finally got it work. Cheers.

  21. […] data between the two systems. At first, this seemed like the most natural choice. Plus, it’s how other people do it. And why wouldn’t they? The API hand-delivers WordPress content as neat, little bundles of […]

  22. how to remove the tags in the output (last image). Having the same problem

    1. Yoren Chang Avatar
      Yoren Chang

      hi, Eddy, Please read the last paragraph and you’ll find the answer.

  23. Hi! Really cool tutorial! However, I ran into a problem with routing.

    If I reload/open an address with /route
    (example: http://site.com/wp-subdirectory/blog/)
    the page loads correctly. But if I try access /route/:slug?
    (example: http://site.com/wp-subdirectory/blog/post-about-something)
    the page redirects to the route specified in .otherwise().

    Any idea how to solve this problem? I currently run on MAMP/Apache environment. I saw some suggestions that it should be configured at .htaccess level, but the examples I tried did not work or broke the wp-api plugin.

    1. Yoren Chang Avatar
      Yoren Chang

      Hi Spikes, can you send me a copy of your scripts.js? I need to check your route settings to see what I can help. Shoot me: yoren[at]1fix.io

  24. Create angular with wordpress have some problem,I write angular in to the child theme ,so i’m not create index.php, i use create angular in wordpress use templates method.

    Now i have a trouble,i want to open the site but it Jump to a blank page

    This is my web site URL,Can you help me!!
    http://www.taiwancards.com/dev/

    1. Yoren Chang Avatar
      Yoren Chang

      Hi Bruce, unfortunately I can’t help you with a custom theme that didn’t come from my tutorials. Good luck.

      1. BRUCEYANG Avatar
        BRUCEYANG

        Still could not solve, thank your reply 🙂

  25. […] Source: Using AngularJS and JSON API in your WordPress theme […]

  26. Jared R Avatar
    Jared R

    Hi! I loved reading the tutorial, but I am having some trouble figuring out the proper file paths to use in my existing WP theme.

    Is there any chance that you could send me a picture of the finished file tree with the partials folder? Or, maybe a zip copy of the tutorial files for reference?

    Any help would be greatly appreciated. Thanks!

    1. Yoren Chang Avatar
      Yoren Chang

      Hey, Jared,

      You can find the final theme for this tutorial here: https://github.com/1fixdotio/angularjs-demo-theme/tree/0ec2b5eac44da8f207af4cb257e3066f78ec9ff0

      (download link on the right)

      I hope that’ll help!

      1. Jared R Avatar
        Jared R

        Yes this is perfect! Thank you

  27. Pakpoom Heng Avatar
    Pakpoom Heng

    Hi Yoren, Thank you for your great post. After I finished reading your post, I have a few question which is very important for me. Don’t it consume a lot of data transfer while we grab the JSON data in order to show just post title and its ID(this chapter => 7. Display WordPress posts with AngularJS and JSON API) ? the JSON data we get from the /wp-json/posts is all posts data in our blog, isn’t it. what is going on if we have tremendous amount of contents and posts ? Do you have the solution that save our data transfer to result the same thing as you demonstrate in this tutorial ?
    Thank you again for the awesome tutorial !!

    1. Yoren Chang Avatar
      Yoren Chang

      Hey, Pakpoom,

      When we call “wp-json/posts/”, we only get the latest x posts from WordPress, the “x” is the number you set in “posts_per_page”. So it’s not that resource consuming as you may think. You can limit the posts passed by WP API with filter parameter: http://wp-api.org/#posts_retrieve-posts

      Thanks for your kind words. Let me know if you have further questions.

      1. Pakpoom Heng Avatar
        Pakpoom Heng

        Thank you so much for the speedy reply. It is all clear now. You are my person of the week award, who help our world better !!! I will keep on reading your other posts. you have done great jobs. thanks again Yoren.

        1. Yoren Chang Avatar
          Yoren Chang

          Thanks for your kind words (again)! Happy learning AngularJS and WordPress!

  28. Xavier Avatar
    Xavier

    Hi,
    Very nice job !
    But I try to use your code in Sage, I write a post:
    https://discourse.roots.io/t/angurlarjs-and-roots/1965/4
    What do you think?
    Thank you

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Xavier,

      I have no experience on working with Sage, though I’ve heard lots of good things about it.

      From the link you provided, I think the last thread made a good point that you’ve got something undefined in your file path so AngularJS can’t found the template file. And from the code you pasted I suppose the undefined object is myLocalized.partials.

      Hope that helps.

  29. David Avatar

    Hi Yoren,

    Using your dynamic base href ‘path’ was returning undefined on my local server running vagrant (worked great in staging). I’m instead using:

    <base href="”>

    This returns null without a path and works both locally and live.

    Does anyone know the best way to have WordPress serve all the pages except mysite.com/app/* allowing Angular to catch /app and handle any route (using location.html5(true), this wouldn’t be needed when set to false).

  30. David Avatar

    Hi Yoren,

    Using your dynamic base href ‘path’ was returning undefined on my local server running vagrant (worked great in staging). I’m instead using:

    <base href="”>

    This returns null without a path and works both locally and live.

    Does anyone know the best way to have WordPress serve all pages except mysite.com/app/* allowing Angular to catch /app and handle any route in my $routeProvider (of course using $locationProvider.html5Mode(true), this wouldn’t be needed when set to false).

    I’ve given add_rewrite_rule a try in my functions.php, but with no success. Any help would be greatly appreciated.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey David, I don’t really understand your question. Can you send me a copy of your theme and be more specific about your issue? [email protected]

  31. David Avatar

    Had a feeling I was babbling, i’ve sent you the theme thank you.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey David, I’ve got the theme and I’m sorry to tell you that I can’t help you with a theme that’s not related to my tutorials. Wish you best luck.

  32. our json output is at the url below
    http://localhost/storage/wp-json/

    after passing the base href to /storage/ i am not able to fetch my post list..
    getting my post ..i have installed my wordpress on localhost and installed wp-api plugin the post is showing in http://localhost/storage/wp-json/.. (storage is my folder name)

    or in simple i am following your tutorial i am stuck on step 5 and not able to fetch up my post.

    1. Yoren Chang Avatar
      Yoren Chang

      Hello Niraj, can you try to install the latest version of my theme (https://github.com/1fixdotio/angularjs-demo-theme/archive/master.zip) and see if it works? If not, paste any error message in the console here so I could help.

      1. I’m having the same problem.

        I have a VirtualHost on localhost and I get: “http://www.omasacalda.dev/wp-json/posts/ 500 (Internal Server Error)”
        Base url is:
        <base href="”>

        Pretty permalinks are activated.

        1. Yoren Chang Avatar
          Yoren Chang

          hello, if you can’t visit “http://www.omasacalda.dev/wp-json/posts/” and it returns 500 error, that means an internal server error so there should be nothing to do with the theme.

          I’d suggest you take a look at your server error logs so you can see the what exactly happened on the server. Good luck!

  33. if we want to change the theme css look can you sujjest me how to do..it.and your theme is working nice.thanks for your help.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Niraj, this theme is for demo purpose so I keep it very simple without any CSS decoration. In the future I’ll introduce the UI Bootstrap so we can integrate our theme with Bootstrap framework.

      As long as you figure out how it works, you can use AngularJS with your own custom CSS with no problem. Good luck!

  34. Thanks for your valuable help.so according to you bootstrap ui would work best..so shall i proceed with bootstrap css intergation and one little doubt shall i work as a child theme or a parent theme.

  35. AND AS I AM USING A CSS OF ANOTHER THEME TO IMPORT IT TO YOUR THEME MAKING YOUR THEME AS A CHILD THEME,IT’S NOT WORKING.. THE CSS IS NOT LOADING..

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Niraj, I don’t quite understand what you’re trying to do, so let’s keep it simple.

      If you’re trying to build a new WordPress theme with Angularjs, build one with UI Bootstrap will be much easier since you don’t have to worry too much about the design aspect. And I’ll say it should be a parent theme.

      If you’re trying to integrate a readymade WP theme with Angularjs, I won’t suggest to use my theme as a child theme cause it’s not what it was made for.

  36. okk thankyou i will start a new theme with bootstrap ui as a parent theme and your articles are really awesome .it had helped me a lot

    1. Yoren Chang Avatar
      Yoren Chang

      You’re welcome! Let me know if you have any question about my tutorials.

  37. Mahmood Chowdhury Avatar
    Mahmood Chowdhury

    Hi Yoren,

    Great article, thanks for sharing. I am currently working on a project where I need to retrieve list of users on the site and display their profile. I have already done it using php and I was wondering how can we retrieve the info using Angular JS. I have installed JSON API users plugin to get the controllers but having difficulty in executing it. Any idea?

    1. Mahmood Chowdhury Avatar
      Mahmood Chowdhury

      Ok so I finally figured out how to retrieve users info 🙂

      1. Yoren Chang Avatar
        Yoren Chang

        Hey Mahmood, good for you!

  38. Hi Yoren,

    Thanks for this write up. I’m currently working on linking WP & REST API up to Foundation App ( http://foundation.zurb.com/apps/docs/#!/angular ) and am curious if you see / have any pointers for routing and views?

    Thanks,

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Adam, I’m quite new to AngularJS so I haven’t test frameworks like UI Bootstrap or Foundation myself. I checked the document of Foundation app and found it uses UI Router for routes and views, so I think the Angular WordPress Seed project might help you to understand how it works: https://github.com/michaelbromley/angular-wordpress-seed. (It uses UI Router too.)

      1. Hi Yoren, Thank you for the response and link. I’ll look into it. If I can get anything working, I’ll let you know.

  39. Jesper Landberg Avatar
    Jesper Landberg

    Hi,

    I have followed ur tutorial and it was very good, thanks!

    One issue I’m having tho is that my posts are loading very slow. The pages load but then it takes like 0.5s for the posts to appear, even tho I only have three posts in total. And it’s the same on all pages, main.html, single.html etc.

    Do you know what might cause this?

    1. Jesper Landberg Avatar
      Jesper Landberg

      If i use console.log(res); on for example a single page where i only use {{post.title}} i get a huge object in the console. Can this be the cause for the slow load times?

      1. Yoren Chang Avatar
        Yoren Chang

        yes, that might be the cause that if you have very huge post content for several posts. In such case you can remove the post content from the JSON response when getting posts.

        In my latest post: https://1fix.io/blog/2015/06/26/adding-fields-wp-rest-api/, it might help to shed some light on manipulating the fields in the JSON response of WP API.

  40. Hello Yoren ,
    Very nice tutorial, it helps a lot … now i want post pagination with numeric digits , you mentioned prev or next pagination but i want numeric pagination , please help me.

    Thanks

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Gaurav, here are some useful links for you:

      I haven’t tried them yet. But they look promising! I hope you’ll figure things out. Cheers.

  41. Hi my json format post is much longer than yours and i can pull it successfully.
    the problem is it only displays 10 posts (recent post) and i would to know how i could request for more since i know i have over 30 posts in my wordpress site.
    im planning to implement an infinite scroll with this but it wont be much of an infinite scroll if i can only pull in 10 posts..
    please help

    1. Yoren Chang Avatar
      Yoren Chang

      Hi Elvin, you can use the “filter” parameter with “posts_per_page” in your API routes. Please refer to another post: https://1fix.io/blog/2015/04/12/pagination-angularjs-wordpress-theme/, you’ll see how it works.

  42. […] Using AngularJS and JSON API in your WordPress theme (1Fix.io) […]

  43. Oh man, I think I spend the last six hours trying to figure out how to get this running in my theme.

    Turns out the Angular route file you are suggesting is bower only. I tried everything until I found this one:
    https://code.angularjs.org/1.4.3/

    and downloaded that angular route file. Now it all goes well.

    The Bower dependency is something you can have a look at. Not everyone can be bothered with that stuff. A plain install/setup would work a lot better (at least save me some hours) and it doesn’t come over as pushy to learn yet another tool before we can get started. Nothing wrong with:

    Now back to your tutorial. Thanks.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Geekaas,

      I wasn’t quite aware but you’re right. I prefer bower in this case because that’ll be much easier for dependencies management.

      Thanks for bringing this up. I may add a project requirement section in the future. And next time if you stuck on something, feel free to contact me. I’ll see if I can save you couple of minutes!

  44. webmasterpro Avatar
    webmasterpro

    How to get comment’s number for a each post?

    1. Yoren Chang Avatar
      Yoren Chang

      It looks like the WP-API doesn’t include the comments count yet: https://github.com/WP-API/WP-API/pull/848

  45. adebowale Avatar
    adebowale

    Nice post, do you have any idea on how I can use key auth in authentication of users before private post are viewed.

    https://github.com/WP-API/Key-Auth

    thanks

    1. Yoren Chang Avatar
      Yoren Chang

      hey Adebowale, haven’t tried this plugin before, but thanks for the info. Soon I’ll write a new post about the oAuth and WP-API, hope that’ll help you in some way.

      1. Many thanks for your blog posts, I’m looking forward to read your next mentioned post about oAuth and WP-API! 🙂

        1. Yoren Chang Avatar
          Yoren Chang

          I’d like to correct my previous comment that since we’re building a WordPress theme, we should use cookie authentication regarding to the suggestions from WP API: http://v2.wp-api.org/guide/authentication/. Stay tuned for the late coming post. 😉

  46. Thank you Yoren Chang, really appreciate your great tutorial, I copied your code on our website and tried to modified our old theme, just wonder how can we separate post from page via $routeProvider, can we use “.when(‘/:[postname’,” instead of “.when(‘/:ID’, ” in your code? Otherwise we need update a lot on our website to keep the google rank, thanks a lot.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Robin, you can use slug to get posts, please refer to: https://1fix.io/blog/2015/02/06/slug-angularjs-wordpress-theme/. And please keep the route structure in your Angular app the same as the permalink structure in your WordPress, so you can benefit from your current Google ranks.

  47. Great tutorial; you`ve got a mistake in the headline 4. – Angular is written the wrong way.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Peter, just updated it. Thanks!

  48. Hi, great tutorial!

    I don’t have experience… and I trie to load images from URL into a .controller, someone can tell me how.. 🙂

    My JSON is this:

    content: “. #gallery-1 { margin: auto; } #gallery-1 .gallery-item { float: left; margin-top: 10px; text-align: center; width: 33%; } #gallery-1 img { border: 2px solid #cfcfcf; } #gallery-1 .gallery-caption { margin-left: 0; } /* see gallery_shortcode() in wp-includes/media.php */

    The controller what I need modified is this to load the post images is this:

    .controller(‘CardsCtrl’, function($scope, TDCardDelegate) {
    var cardTypes = [
    { image: ‘max.jpg’ },
    { image: ‘ben.png’ },
    { image: ‘perry.jpg’ },
    ];
    Thanks in advance,

  49. Yoren Chang Avatar
    Yoren Chang

    Hi Jujes, I don’t quite understand what you’re trying to do, but you may refer to another post: https://1fix.io/blog/2015/03/22/angular-slick-wordpress/ to see if that helps.

  50. Hai YOREN CHANG,
    I am beginer to both wordpress and angularjs. from your great tutorial i am able to display all post content successfully. now i am trying to add third party comment system (disqus) to the each post.
    i installed disqus coment plugin to wordpress, then tested with wordpress default theme. disqus comment will shown in that theme.
    after that i activated above theme (angularjs+wordpress) but comment box is not showing. can you suggest any solution to above problem,
    thank you

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Nithin,

      I haven’t tried the Disqus WordPress plugin but I guess you should try the universal code version instead of the plugin: https://disqus.com/admin/universalcode/.

      Because we don’t use WP template tags in our AngularJS WP theme, so the Disqus plugin won’t work if it just hooks to the filter like the_content.

  51. hay, i want make mobile app and we can post comment in the app???

    thank’s before

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Amar,

      Check out Roy’s Angular WordPress Theme project https://github.com/royboy789/Angular-Wordpress-Theme for more details about comments.

  52. Hello, Yoren.

    I really like your work on Angular + WP API integration and currently working on a project using this as the foundation.

    I’m a beginner in AngularJS and your code really help me!

    Now i’m trying to integrate a Formidable form to the theme but I can’t seem to integrate it properly. Do you ever had any experience with it?

    I have successfully display the form, but there are no validation and thank you after I press submit. I search around and found Formidable API, but still has no idea how to properly parse the form and get thank you after submit. I really hope you can help me here. 🙂

    Thank you!

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Ade,

      I haven’t use Formidable but my best guesses are:
      1) There might be JavaScript conflicts so the validation doesn’t work, if so, you need to debug the JS code.
      2) We need to figure out how Formidable get the “Thank you” message working. If it hooks the message to filters like “the_content”, you need to be sure you do use that filter in your theme.

      Let me know if you need further assistance. Cheers.

  53. I loved the write-up, but I have a question, how does using the rest-api and ajax affect content SEO?

    I see a problem with Google being able to index the content if it is not generated until a client visits the site.

    The only thing I can think of is submitting a detailed sitemap that lays out what content is supposed to be where in your url structure.

    Any thoughts?

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Ronald, I’ve answered a related question here: https://1fix.io/blog/2015/02/06/slug-angularjs-wordpress-theme/#comment-6526

      Hope that’ll clarify some myth about SEO (for a JS heavy app). Let me know if you have any further question. Cheers.

  54. Why didn’t you run wp_enqueue_script on the angular.js file? you only did wp_register_script? do you enqueue some files and register others? How do you know when to enqueue and when to register?

    wp_enqueue_script(
    ‘my-scripts’,
    get_stylesheet_directory_uri() . ‘/js/scripts.js’,
    array( ‘angularjs’, ‘angularjs-route’ )
    );

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Mike, the wp_enqueue_script() can only be run in a PHP file since it’s a PHP function. You can actually enqueue each script right away without registering it, and just remove the dependencies from my-scripts script.

      For more info, the WP Codex might help: https://codex.wordpress.org/Function_Reference/wp_enqueue_script.

  55. Hi, I am trying to follow the tutorial but when inserting the I am getting the following error:

    “`TypeError: Cannot read property ‘replace’ of undefined
    at Cb (angular.js:11406)
    at hf.a.$get (angular.js:12236)
    at Object.e [as invoke] (angular.js:4478)
    at angular.js:4295
    at d (angular.js:4437)
    at Object.e [as invoke] (angular.js:4469)
    at angular.js:4295
    at d (angular.js:4437)
    at Object.e [as invoke] (angular.js:4469)
    at angular.js:7080
    “`

      1. Thanks Yoren, yes it was that problem. Something in the new wordpress forcing // as the protocol and not http: very strange.

        Now my only issue is that the url /[post-id] does not work. I get a 404 for this, how to make wordpress recognise the URL?

        1. Yoren Chang Avatar
          Yoren Chang

          Hi Tom, the only thing I can think of is have you enabled the permalink? But if you haven’t the WP API wouldn’t work at all so I’m out of luck…

          But still, please make sure you’ve set the routes right in AngularJS or just test with my theme. Good luck!

  56. Thank you for this great tutorial!!!
    It was very useful for me =)

    I found some outdated code, in angular 1.4.7 for example,
    we need to change this:

    $locationProvider.html5Mode(true);

    to this:

    $locationProvider.html5Mode({
    enabled: true,
    requireBase: false
    });

    Thanks

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Alex, thanks for the notice. But referring to the Angular documentation here we can see html5Mode can take both boolean and object. So I’ll say either way should work well in Angular 1.4.7. (I just tested with 1.4.3)

  57. ali imran Avatar

    Oh yes it really informative post, I have read it complete really good. AngularJs is wonderful features. Some more great and high rating themes with AngularJS.
    http://alichowdhary.com/2015/12/17/7-high-rating-top-wordpress-angularjs-enable-themes/

    Regards:
    Ali Imran

    1. Yoren Chang Avatar
      Yoren Chang

      Hi Ali, Good to know such great themes in the wild!

  58. Hey Yoren, Very interesting tutorial. Love from WP devs in Sri Lanka 🙂

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Dinusha, thanks for stopping by. Feel free to let me know your thoughts 😉

  59. Tan Nguyen Avatar
    Tan Nguyen

    Hi Yoren Chang,

    I have multiple post type, now I want to get 1 latest posts in all articles of the multiple post type.

    Regards,

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Tan, this post http://scottbolinger.com/custom-post-types-wp-api-v2/ from Scott Bolinger will definitely help you with it. Just check it out.

  60. Hi Yoren, Thank you for the great tutorial mate.
    I am front-end developer with ace in JS, and due to lack of knowledge in PHP and often being stuck I have decided to move on to JSON-REST for my next WP Project. I’m not sure why even after copying all of the content my index.php is not showing the view, may be the data is not binding with the view. So can you please help me put here.

    Code files here : https://gist.github.com/sandiprb/f379d06e1eb24e49ace4

    PS : my json request’s proper as I’m able to fetch the data in browser through direct get in URL.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey, Sandip,

      I noticed that you set the base href to “jsonapi”, it would only work if you do host your site in such subdirectory in the site’s root directory.

      You can update the base href to the following code:
      https://github.com/1fixdotio/angularjs-demo-theme/blob/wp-api-v2/index.php#L4

      If it’s still not working, can you check your console and paste the error message to me?

  61. main.html not found.

    no localize myLocalize.
    $routeProvider
    .when(‘/’, {
    templateUrl: myLocalized.partials + ‘main.html’,
    controller: ‘Main’
    });

    1. Yoren Chang Avatar
      Yoren Chang

      Hey can you be more specific on what’s the problem you met?

  62. Hi Yoren,
    I’m planning to display some data from SQL Server. Can I create REST API and pass data using JSON (e.g. http://dev.example.com/REST/data/)? Do you have any idea how to consume json api in wordpress?

    Thanks,
    Bill

    1. Yoren Chang Avatar
      Yoren Chang

      Bill, You can definitely create your own REST API for your app. Unfortunately I don’t know pretty much on how to accomplish it so can’t be helpful for you. Cheers.

  63. Hi, I’m using WordPress REST API (Version 2), on stage 7 to display posts, i get this as output:

    {“rendered”:”Hello world!”}

    Any idea why?

  64. Figured it out. I have to use

    post.title.rendered

    because my JSON comes as

    title: {
    rendered: “Hello world!”
    },

    Thanks.
    Very helpful article by the way.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey glad you figured that out and thanks for your kind words.

  65. […] making a website with WordPress and I’d like to use Angularjs. I’ve followed this manual, but I’ve some problem with ng-app. This is my simple page that works […]

  66. At Step 5, ng-view is not working for me. The only thing I did differently than you is put the html in a custom page template instead of index.php

    1. Yoren Chang Avatar
      Yoren Chang

      Hi Tim,

      Yep the default WordPress routes might be conflict with the Angular routes we’ve set. That’s why in this series I use no other WordPress templates, but only index.php.

  67. Thank you so much for sharing this post.

  68. Hi Yoren,
    ‘wp-json/posts/’ at line 16 and 21 in file script.js is not working, So replaced the same with ‘index.php/wp-json/posts/’. can we make this and is it correct ?

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Manohar, You need to enable permalink when using WP-API plugin to use the default routes.

  69. Hi Yoren, How can i enable permalink feature. Pls can you guide me? appreciate for your quick reply.

    1. Yoren Chang Avatar
      Yoren Chang

      Please refer to https://codex.wordpress.org/Using_Permalinks, choose any one other than the default option.

  70. Problem solved. Thank you Yoren.

  71. Hello,
    i have a problem at the step 5, i haven’t “this is the main files” that appear

    could you help me?

    1. Yoren Chang Avatar
      Yoren Chang

      Can you provide me with some more info? Like if there’s any error log in your console?

      1. Hello!, i did it without AngularJS Route and it’s work. but now i would like to search between to number. I have something like
        name: product1 , price: 5
        name: product2 , price: 9

        {{product.name}} – {{product.price}}

        the input search on the name is OK
        the input search on the price is OK

        but i don’t know how to search with range

        for example products with min price 6$ and max price 10$ (with two input : “price min” and “price max”) for show only product2.

        Thank you for you help and for you tutorial

        1. Yoren Chang Avatar
          Yoren Chang

          Hey Rom, complex search query is off topic so I can’t provide free support at this moment. I believe you can definitely find related topics somewhere else. Good luck!

  72. Great solution, I like it! But I’m having an issue…

    If I put ng-app in the header without a value, things work fine. If I use a value (e.g. ng-app=”app”), I get $injector:modulerr error and the script doesn’t work.

    Any idea what could be causing this?

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Kevin, I can’t tell without reading your code but can you make sure you’ve set the right module name in your js code: https://github.com/1fixdotio/angularjs-demo-theme/blob/0.1/js/scripts.js#L1?

  73. Hi, thank you this is the best angular-js tutorial I’ve found so far :). One thing, I tried the codes on my wordpress multi site, found that returned 404 error in my console, so that the recent posts didn’t show up. Anyone facing the same issue, please try this code: <base href="”> to fix that error. Works fine on my system 🙂

  74. Edited: instead of

    Thank you 🙂

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Akmal,

      From the latest version of this theme, I’ve changed the base href into:
      https://github.com/1fixdotio/angularjs-demo-theme/blob/wp-api-v2/index.php#L4. You can check if it works for multisite WordPress. Thanks!

  75. Thank you for the help.

    1. Yoren Chang Avatar
      Yoren Chang

      You’re very welcome!

  76. […] Angularjs wordpress theme creation […]

  77. Charles Avatar

    Hi Yoren,
    Is it possible to incorporate angularjs to just a testing page and not touching the global theme?

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Charles, yes that’s definitely doable. You can create a page template and incorporate this tutorial. I believe that would work.

  78. thanks for sharing

    1. Yoren Chang Avatar
      Yoren Chang

      You’re very welcome. 🙂

  79. So, a little bit of theory here… Are we essentially invoking Angular via a special route (main.html) that WordPress normally wouldn’t be responding to? So WordPress just becomes a database interface layer via WP-API?

    I couldn’t tell if you showed off any of Angular’s dynamic updating (i.e. SPA stuff) with this demo…

    Interesting work, thank you.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Emily, you can download the theme from the official repo: https://github.com/1fixdotio/angularjs-demo-theme and give it a go. This post just the first one of a series of tutorials: https://1fix.io/angularjs-wp-rest-api/. If you’re interested in building SPA with Angular 1.x and WP, just check it out.

  80. […] you to Yoren Chang for her walkthrough that helped form this […]

  81. Greetings! Thx for great tutorial!

    Could U be so kind, and give me some more help?

    The problem is to get all tags assigned to each post, so I can’t just understand how to get them in right way.

    1. Yoren Chang Avatar
      Yoren Chang

      Hi Greg, you can try routes in format like: http://[domain]/wp-json/wp/v2/tags?post=[post id].

  82. Mangesh Avatar

    sorry by mistake it my code is not fully visible in my last comment

    index.php
    ________________________________________________________________

    AngularJS Demo Theme

    <a href="”>AngularJS Demo Theme

    Hello, {{name}}!

    ©

    ____________________________________________________________________
    functions.php
    ____________________________________________________________________
    trailingslashit( get_template_directory_uri() ) . ‘partials/’
    )
    );
    }
    add_action( ‘wp_enqueue_scripts’, ‘my_scripts’ );
    ?>

  83. Nathan Keeys Avatar
    Nathan Keeys

    Great article Yoren! I’m a super noob at Angular but Ive been trying to work through this article for a final project for my class. I’ve managed to get the json data on to my app but the post aren’t being routed. This is what my page looks like when I load it.

    AngularJS Demo Theme

    {“rendered”:”Hey”}
    {“rendered”:”Wudup”}
    {“rendered”:”Hello world!”}

    The whole object property seems to be printing instead of just the attribute and when I click on them they dont direct me. Not sure if its a ng-route issue. lol going slightly crazy.

    1. Yoren Chang Avatar
      Yoren Chang

      Hi, Nathan,

      Have you checked the second post: https://1fix.io/blog/2014/11/13/angularjs-wordpress-theme-ngbindhtml/ which may be related to your problem.

      Also be sure to check the Github repo and see if it can work on your server: https://github.com/1fixdotio/angularjs-demo-theme.

  84. Thanks so much! The ng-bind-html worked. Only issue now is that I’m unable to get to the content.html by clicking on the main.html post anchors.

    Looking at this part of the main.html, post.ID should direct to the post of the article thats clicked. am I missing something in the anchor link?


    {{post.title}}

    here’s my js:

    angular.module(‘app’, [‘ngRoute’, ‘ngSanitize’])
    .config(function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);

    $routeProvider
    .when(‘/’, {
    templateUrl: myLocalized.partials + ‘main.html’,
    controller: ‘Main’
    })
    .when(‘/:ID’, {
    templateUrl: myLocalized.partials + ‘content.html’,
    controller: ‘Content’
    });
    })
    .controller(‘Main’, function($scope, $http, $routeParams) {
    $http.get(‘http://localhost:8888/NK_Head/wp-json/wp/v2/posts/’).success(function(res){
    $scope.posts = res;
    });
    })
    .controller(‘Content’, function($scope, $http, $routeParams) {
    $http.get(‘http://localhost:8888/NK_Head/wp-json/wp/v2/posts/’ + $routeParams.ID).success(function(res){
    $scope.post = res;
    });
    });

  85. Sorry here’s my main.html expression too.


    {{post.title}}

  86. Got it working! Thanks for your help. The ID key needed to be lowercase.

    1. Yoren Chang Avatar
      Yoren Chang

      cool! Glad you figured that out.

  87. […] you to Yoren Chang for her walkthrough that helped form this […]

  88. How to use angular js in one custom page template in WP?

    1. Yoren Chang Avatar
      Yoren Chang

      Sorry it’s a bit late, looks like you got the same issue as: https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/#comment-6494. Check if you set the right base href would be a nice first step.

  89. Hi , Thanks for this tutorial , but i am getting error of undefined add_action function . The script files can not be called. Can you help me please

    1. Yoren Chang Avatar
      Yoren Chang

      It’s weird. If you put my snippets in functions.php, no way this could happen…

  90. Yoren Chang .. You rockz..

    Simple and informative post to start the development. This is the best article i have seen internet while searching about this topic. Keep this good works

  91. Hi Yoren,

    Thank you for explaining this so well. I was able to follow all steps up to step 7, where I can’t seem to get the right result.

    Instead of bullets with the post titles of my posts , I just get five bullets (even though I only have one post…). Seems like I can’t properly connect to my posts in JSON format. Any idea how I can solve this?

    Perhaps additionally: I can access wp-json/posts through Postman so the WP REST API seems to work fine.

    Help is much appreciated. Thank you.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Brenda,

      So you get five bullets without post title? Interesting… Have you tried to use my theme files to test?

  92. Hi Yoren,
    Your completed theme is based on REST API v2, and when I install that, I can’t navigate to any endpoint anymore. (like /wp-json/wp/v2/categories)

    My issue just became a little more interesting:
    When I use: {{posts}} I get the JSON result for five list items, but they are all the same post.
    When I use: {{post[0].title}} I get a perfect title of my first post.
    But when I use: {{post.title}} I get absolutely nothing.

    I remember having the same problem on my first attempt, and solving it but I wish I could remember how. 🙂

    1. Yoren Chang Avatar
      Yoren Chang

      Ah my theme might be just not working with REST API in WP core. I actually didn’t follow it up for a while.

  93. Dushyant Avatar

    I am getting the following error: (Help me sort out this) https://docs.angularjs.org/error/$injector/modulerr?p0=app&p1=TypeError:%20$locationProvider.html5mode%20is%20not%20a%20function%20%20%20%20at%20http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fjs%2Fscripts.js%3Fver%3D4.7:3:27%20%20%20%20at%20Object.invoke%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:43:175)%20%20%20%20at%20d%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:41:64)%20%20%20%20at%20http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:41:188%20%20%20%20at%20q%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:7:351)%20%20%20%20at%20g%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:40:488)%20%20%20%20at%20eb%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:45:56)%20%20%20%20at%20c%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:21:19)%20%20%20%20at%20Mc%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:21:332)%20%20%20%20at%20pe%20(http:%2F%2Flocalhost%2Fwordpress%2Fwp-content%2Fthemes%2Fwpangular%2Fangular%2Fangular.min.js%3Fver%3D4.7:20:1

  94. Nice tutorial, am kind of struck. How do I make the html tags that are inside the json data to normal html tags in html

  95. Thanks Yoren for this brief information about angularjs. I’ve been hearing about this before but haven’t tried using it. I was studying and searching about on what else can I do with wordpress and happen to came across your site.

  96. Good Information. Thanks for sharing

  97. Excellent beat ! I would like to apprentice while you amend your site, how
    could i subscribe for a blog website? The account
    helped me a appropriate deal. I were tiny bit familiar of this your broadcast provided bright clear idea

  98. hi, this is my fix for ngRoute:
    ———————————————
    .controller(‘Main’, function ($scope, $http){
    $http({
    method: ‘GET’,
    url: ‘wp-json/posts/’
    }).then(function (response) {
    console.log(response, ‘res’);
    $scope.posts = response.data;
    },function (error){
    console.log(error, ‘can not get data.’);
    });
    });
    —————————————————-
    ‘success’ is not a function it has been removed, use .then() instead

  99. I am really enjoying the theme/design of your web site. Do you ever run into any web browser
    compatibility problems? A small number of my blog visitors have complained about
    my website not operating correctly in Explorer but
    looks great in Safari. Do you have any recommendations to help
    fix this issue?

  100. Hey there, You have done a great job. I’ll certainly digg it and
    personally recommend to my friends. I’m sure they will be
    benefited from this web site.

  101. Hello ,

    Nice article but I am not able to make AngularJS Route work. can anyone please help

  102. Things are very open and intensely clear, explanation of issues was truly informative.

  103. Nice article. Thanks for sharing this.

  104. Thanks for the blogger for such a great article…
    All the issues I faced was clearly explained

  105. Wonderful article! Thanks for sharing….

  106. Great Article… I love to read your articles because your writing style is too good, it is very helpful for all of us and I never get bored while reading your article because they are becomes more and more interesting from the starting lines until the end…

  107. HIGS- the best thesis writing or dissertation writing service in India, we explain to you about thesis writing, thesis writing definition and we offer endless thesis writing services or dissertation writing. We offer the best thesis writing help for all our clients across the globe. With us, you will definitely achieve the goal of success. Our team always gives our hands in providing help for thesis writing and we extend of horizons of knowledge in many places such as PhD thesis writing service in Chennai, Delhi, Hyderabad, Bangalore, Kerala, and more. With our great help in thesis writing service, you will get the best thesis writing help by meeting the high-level standard.

  108. Thanks for the tips to use AngularJS and JSON API in Your WordPress Theme. I think your code can definitely help me.

  109. […] Using AngularJS and JSON API in Your WordPress Theme Yoren Chang (en ligne) sur  https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/&nbsp; [consulté le : 23 septembre […]

Leave a Reply

Your email address will not be published. Required fields are marked *