将解析注入指令控制器



我正在使用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
         }
     }
})

但这不起作用-data参数会导致UnknownProvider错误。独立定义指令控制器并在指令中按名称设置它具有相同的结果。

我或多或少明白为什么会发生这种情况,但有两个问题:

  1. 有办法做我想做的事吗
  2. 我应该试着去做,还是已经陷入了反模式

您不能在指令中使用解析,但您可以将状态中解析的结果传递给指令,我认为该指令可以实现您想要的功能。

您可能希望更新您的状态定义,以包括一个控制器,并在指令上设置一个参数:

.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

他们简化了api。查看此线程:

https://github.com/angular-ui/ui-router/issues/2664#issuecomment-204593098

在0.2.19中,我们将$resolution添加到$scope中,允许您执行";路由到组件模板";样式

模板:<my-directive input="$resolve.simpleObj"></my-directive>

最新更新