我有一个Angular 1.3模块,看起来像这样(该指令要求使用,存在一个父指令controllerAs
):
angular.module('fooModule', [])
.controller('FooController', function ($scope) {
this.doSomething = function () {
// Accessing parentDirectiveCtrl via $scope
$scope.parentDirectiveCtrl();
};
})
.directive('fooDirective', function () {
return {
// Passing in parentDirectiveCtrl into $scope here
link: function link(scope, element, attrs, parentDirectiveCtrl) {
scope.parentDirectiveCtrl = parentDirectiveCtrl;
},
controller: 'FooController',
controllerAs: 'controller',
bindToController: true,
require: '^parentDirective'
};
});
在这里,我只是$scope
用来通过parentDirectiveCtrl
,这似乎有些笨拙。
require
没有链接功能,还有另一种方法可以从指令的控制器访问-ed控制器吗?
您必须使用该link
函数来获取require
-ed控制器,但无需使用范围将控制器的引用传递给您自己的。而是直接将其传递给您自己的控制器:
.directive('fooDirective', function () {
return {
require: ["fooDirective", "^parentDirective"],
link: function link(scope, element, attrs, ctrls) {
var me = ctrls[0],
parent = ctrls[1];
me.parent = parent;
},
controller: function(){...},
};
});
但是要小心,因为控制器在链接之前运行,所以在控制器内部this.parent
为undefined
,直到链接功能运行之后。如果您需要确切知道何时发生,可以随时使用控制器函数将parentDirective
控制器传递给:
link: function link(scope, element, attrs, ctrls) {
//...
me.registerParent(parent);
},
controller: function(){
this.registerParent = function(parent){
//...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句