如何使用Angular js获取Wordpress Post

时间:2017-02-15 18:16:20

标签: angularjs wordpress wordpress-rest-api

我正在尝试使用wordpress rest api插件和$ http服务将我的角度应用程序连接到WordPress CM但是,由于某种原因数据不会返回。可以使用wordpress提供正确的方法来检索wordpress的数据api插件?

下面我列出了包含我的html和JavaScript的代码。另外,我已经列出了我正在尝试获取测试数据的本地休息api。

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.2/angular-sanitize.js"></script>
</head>
<body>
<div class="masthead" np-app="myApp">
                <div class="item">
                    <div class="masthead-content">
                        <div class="copy">
                            <div class="container">
                                <div class="row">
                                    <div class="col-md-6"  ng-controller="Ctrl">
                                    <div ng-repeat="post in posts | limitTo: 1">
                                        <h2 ng-bind-html="post.title.rendered">{{posts}}</h2>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    <script>

var app = angular.module('myApp', ['ngSanitize']);
    app.controller('myCtrl', function($http, $scope) {
        $http.get("http://localhost/wp/wp-json/wp/v2/posts/4").success(function(data) {
        $scope.posts = data;

    });
});

</script>

    

1 个答案:

答案 0 :(得分:0)

调用REST的REST API没问题

$http.get('https://yourblog.com/wp-json/wp/v2/posts/?categories=1&per_page=2&orderby=id&order=asc&page=1').
    then(function(response) {
        console.log(response);
        $scope.posts = response.data;
    });

此代码在我的AngularJS或离子应用程序中运行

<div ng-repeat="post in posts">
 <h2>{{post.title}}</h2>
</div>