将解析注入指令控制器 [英] 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:
- 有什么方法可以做我想做的事情?
- 我应该尝试执行此操作,还是在这里滑入反模式?
推荐答案
您不能在指令中使用resolves,但是您可以将状态下已解析的结果传递给我认为可以完成您所要查找的指令
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: '='
}
};
})
这是一个示例插件: http://plnkr.co/edit/TOPMLUXc7GhXTeYL0IFj?p=preview
这篇关于将解析注入指令控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!