[英]$broadcast timing issue in angularJS, how to ensure directive is created before broadcasting
我在angularJS中遇到$ broadcast问题。 我的控制器正在使用$ compile函数在页面加载时向DOM动态添加指令元素。
$('#container').prepend($compile('<myDirective></myDirective>')($scope));
$scope.$broadcast('loadIt', stuffIneedLoaded);
我想做的是在创建指令时调用指令作用域函数,因此我使用了$ broadcast。 现在发生的是,在伪指令完成渲染之前调用了$ broadcast,因此伪指令中的scope。$ on从未听到广播。
从指令链接功能:
link: function (scope, element, attrs) {
scope.$on('loadIt') = function (stuffToLoad) {
//stuff to load
}
}
我需要使用广播的原因是因为我需要从控制器发送指令数据。
提琴不起作用,只是样板可以帮助传达我正在拍摄的内容:
有任何想法吗? 谢谢大家!
我将使用两个指令,并从另一个调用。 此外,编译后将调用调用广播的作用域方法。 就像是:
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.recall = function() {
$scope.$broadcast('loadIt');
};
});
fessmodule.$inject = ['$scope'];
fessmodule.directive("myDirective", function() {
return {
restrict: 'E',
template: "<div>test code</div>",
link: function (scope, element, attrs) {
scope.$on("loadIt", function() {
console.log('in myDirective on');
});
}
}
});
fessmodule.directive('directiveFoo', function($compile) {
return {
controller: function() {
console.log('in foo ctrl');
},
link: function (scope, element, attrs) {
var elem_0 = angular.element(element[0]);
var a_input = angular.element($compile('<my-directive></my-directive>')(scope));
elem_0.prepend(a_input);
scope.recall();
}
}
});
演示小提琴
附带说明:
我强烈建议避免在控制器中进行任何DOM更新/操作。 使用指令。 通过这种方式,我们可以控制和跟踪呼叫队列中的大多数问题。
这很老,但是今天我用这种方式解决了类似的问题:
module.controller('moduleCtrl', function ($scope, $interval) {
$scope.triggerEvent = function() {
var promise =
$interval(function () {
if (scope.$$listenerCount["loadIt"] == null
|| scope.$$listenerCount["loadIt"] === 0)
return;
scope.$broadcast("loadIt");
$interval.cancel(promise);
}, 200);
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.