因此,当在子指令中使用指令属性 require: '^ParentCtrl'
时,我总是完全相反地执行此操作。然后使用 require 调用父函数;但是,我需要反过来做。
问题:
如何从父指令触发子指令中函数的执行。
注意:
1. 子指令在 link:
中没有任何功能
2. 本质上我想要一个反向需求。
父指令:
'use strict';
angular.module('carouselApp')
.directive('waCarousel', function() {
return {
templateUrl: 'views/carousel/wa.carousel.html',
controller: function($scope) {
var self = this;
// this function is being called based on how many pages there are
self.carouselElLoaded = function(result) {
var count = 1;
Carousel.params.pageRenderedLength += count;
//when all the pages are loaded
if (Carousel.params.pageRenderedLength === Carousel.params.pageLength) {
Carousel.params.carouselReady = true;
// !!!!!!!! Trigger will go here!!!!!!!!!//
ChildCtrl.drawHotspots(); // (**for placement only**)
} else {
Carousel.params.carouselReady = false;
}
};
}
}
})
子指令:
'use strict';
angular.module('carouselApp')
.directive('waHotspots', function() {
return {
require: '^waCarousel',
link: function (scope, element, attrs, ctrl) {
//call this directive based on how
scope.drawHotspots = function () {...};
}
})
最佳答案
这可以通过让父 Controller 通过您创建的定义良好的 API 与子 Controller 对话来实现。这个想法是,您希望通过让每个各自的 Controller 尽可能少地了解彼此来保持父指令和子指令之间的松散耦合,但仍然有足够的知识来完成工作。
为此,从子指令中获取父指令,并让子指令在父 Controller 中注册自己:
子指令:
require: '^parentDirective',
controller: function(){
this.someFunc = function() {...}
},
link: function(scope,element,attr, parentCtrl){
parentCtrl.register(element);
}
然后在你的parent指令中,实现register函数,并获取child的controller,需要的时候调用child的函数:
父指令:
controller: function(){
var childCtrl = undefined;
this.register = function (element) {
childCtrl = element.controller();
}
this.callChildFunc = function (){
childCtrl.someFunc();
}
},
link: function (scope,element){
var ctrl = element.controller();
ctrl.callChildFunc();
}
关于javascript - 从它的父[angularJS]触发子指令中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27698454/