2016-12-09 50 views
0

我想顯示我的WordPress的帖子與已安裝的插件WP-REST v2從穀倉AngularJS獲取數據但是這是一個問題。我無法顯示它並根據這篇文章進行編碼。WP-json不顯示angularJS

https://amielucha.com/angularjs-json-rest-api-with-wordpress

所以我的主要議題是如何將它與angularjs。

這是我的代碼:

app.js:

(function() { 
var app = angular.module('app', ['ngRoute']), 
    api = {}; 

// JSON content Location 
api.query = 'http://myy.website/dlrz/wp-json/wp/v2/posts/'; 

app.config([ '$routeProvider', '$locationProvider', '$qProvider', function($routeProvider, $locationProvider, $qProvider) { 
    // Enable HTML5 Mode 
    $locationProvider.html5Mode(true); 

    // configure routing 
    $routeProvider 
     .when('/', { 
     templateUrl: myLocal.partials + 'main.html', 
     controller: 'Main' 
    }); 

    $qProvider.errorOnUnhandledRejections(false); 
}]); 

// Set Controller and get JSON-Data 
app.controller('Main', [ '$scope', '$http', '$routeParams', '$sce', function($scope, $http, $routeParams, $sce) { 
    $http.get(api.query).then(function(res){ 
     $scope.posts = res; 
     // interate through each field to set it as trusted 
     angular.forEach(res, function(value, key) { 
      // trust each title and excerpt in the object 
      this[key].title.rendered = $sce.trustAsHtml(value.title.rendered); 
      this[key].excerpt.rendered = $sce.trustAsHtml(value.excerpt.rendered); 
     }, $scope.posts); 
     console.log($scope.posts); 
     console.log($sce); 

    }); 
}]); 
})(); 

main.html中:

<section> 
<article class="well" ng-repeat="post in posts"> 
    <header> 
     <h1 ng-bind-html="post.title.rendered"> 
      {{post.title.rendered}} 
     </h1> 
    </header> 
    <div class="post-content" ng-bind-html="post.excerpt.rendered"> 
     {{post.excerpt.rendered}} 
    </div> 
</article> 

的index.php:

<?php /*get_header(); */?> 


<!DOCTYPE html> 
<html ng-app="app"> 

    <head> 
     <!-- Required meta tags always come first --> 
     <meta charset="utf-8"> 
     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 
     <meta http-equiv="x-ua-compatible" content="ie=edge"> 
     <base href="<?php echo site_url();?>/"> 

     <title> 
      <?php bloginfo('name'); ?> 
     </title> 
     <?php wp_head(); ?> 
    </head> 
    <body> 
     <h1>Hello World!</h1> 

     <div ng-view></div> 


     <footer> 
      &copy; <?php echo date('Y'); ?> Dart Liga Verband Zürich 
     </footer> 

    </body> 
</html>  
<?php wp_footer(); ?> 
<?php/* get_footer(); */?> 

這是json文件: http://myy.website/dlrz/wp-json/wp/v2/posts

+0

有你,或者你有什麼檢查的執行console.log爲$ scope.posts任何錯誤? –

+0

解析$ http.get的promise後,立即設置'$ scope.posts = res'。如果您稍後循環查看結果,則不希望這樣做。什麼部分不起作用?正在提取數據?在視圖中顯示它? –

+0

我刪除了$ scope.posts,但現在我無法在視圖上顯示它,你可以在控制檯中看到:http://myy.website/dlrz/ –

回答

1

問題在於如何從響應中獲取數據。您正在使用

$scope.posts = res; 

,但它應該是

$scope.posts = res.data;