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 thoughts on “Using AngularJS and JSON API in Your WordPress Theme”

  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

    Reply
  2. 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

    Reply
  3. 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!!

    Reply
  4. 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

    Reply
  5. 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,

    Reply
    • 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. 🙂

      Reply
  6. 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.

    Reply
  7. 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

    Reply
  8. 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!

    Reply
    • 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.

      Reply
  9. 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

    Reply
  10. 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?

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

      Reply
  11. 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

    Reply
  12. 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.

    Reply
    • 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

      Reply
  13. 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/

    Reply
  14. 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!

    Reply
  15. 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 !!

    Reply
    • 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.

      Reply
      • 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.

        Reply
    • 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.

      Reply
  16. 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).

    Reply
  17. 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.

    Reply
    • 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.

      Reply
      • 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.

        Reply
        • 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!

          Reply
    • 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!

      Reply
  18. 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.

    Reply
    • 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.

      Reply
  19. 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?

    Reply
  20. 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?

    Reply
    • 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?

      Reply
  21. 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

    Reply
  22. 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

    Reply
  23. 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.

    Reply
    • 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!

      Reply
  24. 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.

    Reply
  25. 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,

    Reply
  26. 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

    Reply
    • 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.

      Reply
  27. 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!

    Reply
    • 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.

      Reply
  28. 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?

    Reply
  29. 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’ )
    );

    Reply
  30. 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
    “`

    Reply
  31. 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

    Reply
    • 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)

      Reply
  32. 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,

    Reply
  33. 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.

    Reply
  34. main.html not found.

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

    Reply
    • 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.

      Reply
  35. 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?

    Reply
  36. 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.

    Reply
    • 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.

      Reply
  37. 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 ?

    Reply
      • 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

        Reply
        • 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!

          Reply
  38. 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?

    Reply
  39. 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 🙂

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

      Reply
  40. 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.

    Reply
  41. 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.

    Reply
  42. 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’ );
    ?>

    Reply
  43. 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.

    Reply
  44. 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;
    });
    });

    Reply
  45. 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

    Reply
  46. 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

    Reply
  47. 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.

    Reply
  48. 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. 🙂

    Reply
  49. 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

    Reply
  50. 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.

    Reply
  51. 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

    Reply
  52. 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?

    Reply
  53. 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…

    Reply
  54. 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.

    Reply

Leave a Comment