将解析注入指令控制器
Injecting resolves into directive controllers
我正在使用 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
错误。独立定义指令控制器和在指令中按名称设置结果相同。
我或多或少明白为什么会这样,但有两个问题:
- 有没有办法做我想做的事?
- 我应该尝试这样做,还是我在这里陷入了反模式?
你不能在指令中使用解析,但你可以将状态中解析的结果传递给我认为完成你正在寻找的指令。
您想更新状态定义以包含控制器并在指令上设置参数:
.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
in 0.2.19 we are adding $resolve to the $scope, allowing you to do "route to component template" style
template: <my-directive input="$resolve.simpleObj"></my-directive>
,
我正在使用 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
错误。独立定义指令控制器和在指令中按名称设置结果相同。
我或多或少明白为什么会这样,但有两个问题:
- 有没有办法做我想做的事?
- 我应该尝试这样做,还是我在这里陷入了反模式?
你不能在指令中使用解析,但你可以将状态中解析的结果传递给我认为完成你正在寻找的指令。
您想更新状态定义以包含控制器并在指令上设置参数:
.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
in 0.2.19 we are adding $resolve to the $scope, allowing you to do "route to component template" style
template:
<my-directive input="$resolve.simpleObj"></my-directive>
,