【发布时间】:2017-10-29 13:47:30
【问题描述】:
我正在尝试创建一个 Angular Factory,它将创建一个可注入对象,我可以在我的应用程序的任何地方使用它。我在 WordPress 主题中执行此操作。工厂应该不用太多代码就可以处理大量的 Javascript 命令。
在我的 assets/js/angular-theme.js 中,我为我的主题创建了可注入对象:
var wpApp = new angular.module('wpAngularTheme', ['ui.router', 'ngResource']);
这应该适用于我的工厂,我尝试在 WordPress 主题的 functions.php 文件中进行排队。我正要按照这里的说明进行操作:
https://docs.angularjs.org/api/ngResource
但 Google 似乎不再支持 angular-resource.js 的 CDN
在这里自己看看:
https://docs.angularjs.org/api/ngResource
如果我是正确的,那么角度文档中的说明似乎已经过时了。无论如何,我继续以这种方式开发我的文件:
assets/js/angular-theme.js:
// To use $resource inside your controller/service you
// need to declare a dependency on $resource.
var wpApp = new angular.module('wpAngularTheme', ['ui.router', 'ngResource']);
//The next step is calling the $resource() function with your REST endpoint.
// This function call returns a $resource class representation which can be
// used to interact with the REST backend. The Posts function is to take the new
// Injectable called $resource
wpApp.factory('Posts', function($resource){
return $resource(appInfo.api_url + 'posts/:ID', {
ID: '@id'
})
});
wpApp.controller('ListCtrl', ['$scope', 'Posts', function($scope, Posts) {
console.log('ListCtrl');
$scope.page_title = 'Blog Listing';
Posts.query(function(res){
$scope.posts = res;
});
}]);
wpApp.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('list', {
url: '/',
controller: 'ListCtrl',
templateUrl: appInfo.template_directory + 'templates/list.html'
})
})
我的模板/list.html:
<h1>{{page_title}}</h1>
<pre><code>{{posts | json}}</code></pre>
functions.php:
<?php
class wp_ng_theme {
function enqueue_scripts() {
wp_enqueue_style('bootstrapCSS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', array(), '1.0', 'all');
wp_enqueue_script('angular-core', 'https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js', array('jquery'), '1.0', false);
wp_enqueue_script('angular-resource', 'https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.6/angular-resource.js', array('angular-core'), '1.0', false);
wp_enqueue_script('ui-router', 'https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js', array('angular-core'), '1.0', false);
wp_enqueue_script('ngScripts', get_template_directory_uri() . '/assets/js/angular-theme.js', array('ui-router'), '1.0', false);
wp_localize_script('ngScripts', 'appInfo',
array(
'api_url' => rest_get_url_prefix() . '/wp/v2/',
'template_directory' => get_template_directory_uri() . '/',
'nonce' => wp_create_nonce('wp_rest'),
'is_admin' => current_user_can('administrator')
)
);
}
}
$ngTheme = new wp_ng_theme();
add_action('wp_enqueue_scripts', array($ngTheme, 'enqueue_scripts'));
?>
但我没有在浏览器上获得 WP REST API 数据呈现。
【问题讨论】:
-
如果可能的话,你能通过小提琴展示吗?
标签: javascript php angularjs wordpress