0

I am currently trying my hand at creating a WP theme using angular JS. I am trying to work through this tutorial: https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/

However, I am near the end of this, and my ng-repeat is not returning a list of my posts.

This is my scripts.js:

angular.module('app', ['ngRoute'])
.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('wp-json/wp/v2/posts/').then(function(res){
    $scope.posts = res;
    });
})
.controller('Content', function($scope, $http, $routeParams) {
    $http.get('wp-json/wp/v2/posts' + $routeParams.id).then(function(res){
        $scope.post = res;
    });
});

And this is the code from my main.html:

<div ng-controller="Main">
<strong>This is the main page</strong>

<ul>
     <li ng-repeat="post in posts">
        <a href="{{ post.id }}">{{ post.title }}</a>
     </li>
    </ul>
</div>

However, when I navigate to my page I only see:

enter image description here

All the scripts seem to be enqueued correctly, and index.php is pulling main.html through, it just doesn't work.

I know it'll be something obvious, but my google foo has let me down

0

It looks like the tutorial you linked is using success, and you've changed it to then.

The success method has been deprecated, so you were correct to do that. However, because then returns data a little differently from success, you'll need to update your $scope.post variable accordingly:

$scope.post = res.data;

You can find a great explanation for the change in this answer.

| improve this answer | |
  • Worked like a charm, thanks for your help, I feel a bit stupid I couldn't find that answer myself now. Also, thanks for including a link to the explanation as well – SRH1984 Jun 25 '17 at 18:57
1

Looking at the post format generated by the REST API I think you should access the title like:

 <li ng-repeat="post in posts">
    <a href="{{ post.id }}">{{ post.title.rendered }}</a>
 </li>
| improve this answer | |
  • Thanks, unfortunately that doesn't seem to be working for me either – SRH1984 Jun 24 '17 at 21:07
  • And the { {post.id }} - is this part working? – Picard Jun 24 '17 at 21:09
  • Sorry, no that bit doesn't seem to work either. – SRH1984 Jun 24 '17 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.