路由器的决心不会注入控制器
我已经想尽一切办法让UI路由器的决心,传递它的值给定的控制器AppCtrl。我使用依赖注入 $注
,这似乎引起问题。我缺少什么?
I have tried everything to get ui-router's resolve to pass it's value to the given controller–AppCtrl. I am using dependency injection with $inject
, and that seems to cause the issues. What am I missing?
路由
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: 'AppCtrl',
controllerAs: 'vm',
resolve: {
auser: ['User', function(User) {
return User.getUser().then(function(user) {
return user;
});
}],
}
});
控制器
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope'];
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
console.log(auser); // undefined
...
}
修改
这里有一个普拉克 http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=$p$ PVIEW
当您使用路线的决心参数作为绑定到该路由控制器依赖注入,您不能使用NG-控制器指令,控制器,因为与服务提供商名称 aname
不存在。它是一个动态的依赖由路由器时,它实例在各自的局部视图要绑定的控制器注入。
When you use route resolve argument as dependency injection in the controller bound to the route, you cannot use that controller with ng-controller directive because the service provider with the name aname
does not exist. It is a dynamic dependency that is injected by the router when it instantiates the controller to be bound in its respective partial view.
还记得返回 $超时
在你的榜样,因为它返回一个承诺,否则你的观点将得到没有任何价值解决,同样的是,如果你使用的情况下 $ HTTP 或返回一个承诺的其他服务。
Also remember to return $timeout
in your example, because it returns a promise otherwise your argument will get resolved with no value, same is the case if you are using $http
or another service that returns a promise.
即
resolve: {
auser: ['$timeout', function($timeout) {
return $timeout(function() {
return {name:'me'}
}, 1000);
}],
在控制器注入决心依赖。
In the controller inject the resolve dependency.
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope','auser']; //Inject auser here
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
vm.user = auser;
}
在视图,而不是NG-控制器,使用用户界面视图
指令:
in the view instead of ng-controller, use ui-view
directive:
<div ui-view></div>
Demo