我正在使用AngularUI路由器(0.2.13)并且具有这样定义的状态
- .state('foo',{
- template:'<div some-directive></div>',resolve:{
- foo:function(SomeService){
- return SomeService.something().promise;
- }
- })
和这样的指令:
- app.directive('someDirective',function(){
- return {
- controller: function(data) {
- // I want `data` to be injected from the resolve...
- // as it would if this was a "standalone" controller
- }
- }
- })
但这不起作用 – 数据参数导致UnknownProvider错误.独立定义指令控制器并在指令中按名称设置它具有相同的结果.
我或多或少知道为什么会这样,但有两个问题:
>有没有办法做我想做的事情?
>我应该尝试这样做,还是我在这里进入反模式?
你不能在指令中使用resolve,但是你可以将在状态中解析的结果传递给我认为可以完成你正在寻找的指令.
您需要更新状态定义以包含控制器并在指令上设置参数:
- .state('foo',{
- template:'Test<div some-directive something="foo"></div>',url: 'foo',resolve:{
- foo:function(SomeService){
- return SomeService.something();
- }
- },controller: function($scope,foo){
- $scope.foo = foo;
- }
- })
然后更新指令以使用此参数:
- .directive('someDirective',function(){
- return {
- controller: function($scope) {
- // I want `data` to be injected from the resolve...
- // as it would if this was a "standalone" controller
- console.log('$scope.something: '+ $scope.something);
- },scope: {
- something: '='
- }
- };
- })
这是一个样本plunker:http://plnkr.co/edit/TOPMLUXc7GhXTeYL0IFj?p=preview