注入解析到指令控制器 [英] Injecting resolves into directive controllers
问题描述
我正在使用 AngularUI 路由器 (0.2.13) 并定义了一个状态
I'm using AngularUI router (0.2.13) and have a state defined as such
.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
错误.独立定义指令控制器并在指令中按名称设置,结果相同.
but this doesn't work - the data
parameter causes an UnknownProvider
error. Defining the directive controller independently and setting it by name in the directive has the same result.
我或多或少明白为什么会这样,但有两个问题:
I more or less get why this is happening, but have two questions:
- 有没有办法做我想做的事?
- 我应该尝试这样做,还是在这里陷入反模式?
推荐答案
您不能在指令中使用解析,但是您可以将状态中解析的结果传递给我认为可以完成您正在寻找的指令的指令.
You can't use resolves in directives, but you can pass the result resolved in the state down to the directive which I think accomplishes what you're looking for.
您希望更新状态定义以包含控制器并在指令上设置参数:
You'd want to update your state definition to include a controller and set a parameter on the directive:
.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;
}
})
然后更新指令以使用此参数:
Then update the directive to use this parameter:
.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
Here's a sample plunker: http://plnkr.co/edit/TOPMLUXc7GhXTeYL0IFj?p=preview
这篇关于注入解析到指令控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!