[英]Trigger a function in a child directive from it's parent [angularJS]
因此,當在子指令中使用指令屬性require: '^ParentCtrl'
時,我一直完全相反。 使用 require 然后調用父函數; 但是,我需要反向執行此操作。
題:
如何從父指令觸發函數在子指令中的執行。
注意:1. 子指令在link:
內沒有任何功能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 () {...};
}
})
這可以通過讓父控制器通過您創建的定義良好的 API 與子控制器通信來實現。 這個想法是你希望通過讓每個控制器盡可能少地了解彼此來保持父指令和子指令之間的松散耦合,但仍然有足夠的知識來完成工作。
為了實現這一點,需要從子指令中獲取父指令,並讓子指令向父控制器注冊自己:
子指令:
require: '^parentDirective',
controller: function(){
this.someFunc = function() {...}
},
link: function(scope,element,attr, parentCtrl){
parentCtrl.register(element);
}
然后在你的 parent 指令中,實現 register 函數,並獲取 child 的控制器,並在需要時調用 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();
}
你總是可以通過 $watch 觸發它。 只需傳入您想要觀看的父作用域值並更改它的值。
家長:
$scope.drawHotspots = false;
模板:
waHotspots the-trigger="drawHotspots"....
兒童指令:
localTrigger: '@' // Receive the value to watch
scope.$watch('localTrigger',function() {
// call drawHotspots if value is set to true
});
這是一個老話題,但我今天來到這里,其他人也可能......
我認為最好的方法是使用Service
angular.module('App').service('SomeService', [SomeService]);
然后將服務注入父子進程......
controller : ['$rootScope', '$scope','SomeService', SomeDirectiveController],
使用該服務相互交談...
在他們的控制器SomeService.setParent(this)
和SomeService.setChild(this)
服務將有一個字段來保存引用:
this.parentCtrl = null;
this.childCtrl = null;//or [] in-case you have multiple childs!
父級中的某處: SomeService.childCtrl.someFunctionInChild()
或者,如果您想要限制訪問,請在服務中將字段設為私有:
var parentCtrl = null;
var childCtrl = null;//or [] in-case you have multiple childs of the same type!
this.callUserFunc = function(param){childCtrl.someFunctionInChild(param)};
和父級中的某處: SomeService.callUserFunc(myparam)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.