Javascript AngularJS中的DetailController和路由
我用这个js脚本制作了一个angular应用程序:Javascript AngularJS中的DetailController和路由,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,我用这个js脚本制作了一个angular应用程序: /** * Services **/ var app; app = angular.module('example.api', ['ngRoute', 'ngResource', 'controllers']); app.factory('Post', ['$resource', function($resource) { return $resource('/api/posts/:id', {post: '@id'}); }]
/**
* Services
**/
var app;
app = angular.module('example.api', ['ngRoute', 'ngResource', 'controllers']);
app.factory('Post', ['$resource', function($resource) {
return $resource('/api/posts/:id', {post: '@id'});
}]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/posts/:id', {templateUrl: "static/js/post_detail.html", controller: "PostListController"})
.when('/posts', {template: '<p>No link selected</p>', controller: "PostDetailController"})
.otherwise({redirectTo: '/posts'});
}]);
/**
* Controllers
**/
var controllers;
controllers = angular.module('controllers', []);
controllers.controller('PostListController', ['$scope', 'Post', function($scope, Post) {
$scope.posts = Post.query();
}]);
controllers.controller('PostDetailController', ['$scope', 'Post', function($scope, Post) {
$scope.post = Post.query();
}]);
/**
*服务
**/
var-app;
app=angular.module('example.api',['ngRoute','ngResource','controllers']);
app.factory('Post',['$resource',function($resource){
返回$resource('/api/posts/:id',{post:'@id'});
}]);
app.config(['$routeProvider',函数($routeProvider){
$routeProvider.when('/posts/:id',{templateUrl:“static/js/post_detail.html”,controller:“PostListController”})
.when('/posts',{template:'未选择任何链接',控制器:“PostDetailController”})
。否则({重定向到:'/posts'});
}]);
/**
*控制器
**/
无功控制器;
控制器=角度。模块('controllers',[]);
controller.controller('PostListController',['$scope','Post',function($scope,Post){
$scope.posts=Post.query();
}]);
controllers.controller('PostDetailController',['$scope','Post',function($scope,Post){
$scope.post=post.query();
}]);
这个html模板:
<div class="row" ng-app="example.api">
<div class="col-md-2" ng-controller="PostListController">
<ul>
<li ng-repeat="post in posts">
{% verbatim %}
<a href="#/posts/{{ ::post.id }}">{{ ::post.id }}</a>
{% endverbatim %}
</li>
</ul>
</div>
<div class="col-md-10" ng-controller="PostDetailController">
<div ng-view></div>
</div>
</div>
-
{%verbatim%}
{%endverbatim%}
我的问题在PostDetailController
中。我不知道如何正确使用$resource
。我刚刚尝试了$scope.post=post.query()
,但我想我可能需要告诉资源查看变量id
我已经看了文档,但还是没弄明白
除此之外,我想知道是否有可能避免网站在将帖子加载到我的PostListController
中之前先显示我的未渲染模板。这并不是一个真正的问题,但在渲染之前网站会闪烁是很难看的
Post.get(id)
获取特定条目您必须注入以获取路由id。现在您可以这样做:
$scope.post=post.get($routeParams.id)
$scope.post=post.get(id)代码>?所以我猜它将是controllers.controller('PostDetailController',['$scope','$routeParams','Post',函数($scope,$routeParams,Post){$scope.Post=Post.get($routeParams.id);})代码>但它会导致资源错误。