【发布时间】:2015-07-03 21:46:00
【问题描述】:
我在 stackoverflow 上发现了一些类似的问题,但没有令人满意的答案。
我更喜欢使用bindToController 和controllerAs 在他们的控制器中保存大部分指令逻辑。
所以标准的通信 beetwen 2 指令看起来像:
<parent-directive>
<child-directive></child-directive>
</parent-directive>
angular.module('app').
directive('parent', function() {
return {
scope: {},
restrict: 'E',
controller: function() {
this.doSomething = function() {
console.log('Consider it done!');
};
},
controllerAs: 'vm'
}
}).
directive('child', function() {
return {
restrict: 'E',
require: '^parent',
link: function($scope, $element, $attrs, parentController) {
parentController.doSomething();
}
}
});
这种模式当然可以按预期工作。但是当我希望 children 指令也使用控制器而不是链接函数时,我必须这样做:
.directive('child', function() {
return {
restrict: 'E',
require: ['child', '^parent'],
controllerAs: 'vm',
controller: function() {
this._parentController = null;
var vm = this;
this.doSomethingInChild = function() {
var iDepnedOnThis = this._parentController.doSomething();
//do something more with above call result...
}.bind(this);
}
link: function($scope, $element, $attrs, controllers) {
var vm = controllers[0];
vm._parentController = controllers[1];
}
}
});
它也有效,但我不确定这是否干净并且是最佳解决方案。 有什么办法可以摆脱 parentController 到 childController 分配到链接功能?
【问题讨论】:
-
@machei:恕我直言,链接问题不能解决我的问题。我们不能保证 $scope.$parent in child 是 parent 指令使用的 $scope。例如。在子指令上使用 ng-repeat 时。
标签: angularjs angularjs-directive