[英]$broadcast timing issue in angularJS, how to ensure directive is created before broadcasting
I'm having a problem with $broadcast in angularJS. 我在angularJS中遇到$ broadcast问题。 My controller is dynamically adding directive elements to the DOM on page load using the $compile function.
我的控制器正在使用$ compile函数在页面加载时向DOM动态添加指令元素。
$('#container').prepend($compile('<myDirective></myDirective>')($scope));
$scope.$broadcast('loadIt', stuffIneedLoaded);
What I want to do is to call a directive scope function upon the directive being created and so I used $broadcast. 我想做的是在创建指令时调用指令作用域函数,因此我使用了$ broadcast。 What is happening now is that the $broadcast is called before the directive is done rendering and so the scope.$on in the directive never hears the broadcast.
现在发生的是,在伪指令完成渲染之前调用了$ broadcast,因此伪指令中的scope。$ on从未听到广播。
From the directive link function: 从指令链接功能:
link: function (scope, element, attrs) {
scope.$on('loadIt') = function (stuffToLoad) {
//stuff to load
}
}
The reason I need to use broadcast is because I need to send the directive data from the controller. 我需要使用广播的原因是因为我需要从控制器发送指令数据。
http://jsfiddle.net/5ReCu/ http://jsfiddle.net/5ReCu/
The fiddle doesn't work, just boilerplate to help convey what I'm shooting for: 提琴不起作用,只是样板可以帮助传达我正在拍摄的内容:
Any ideas? 有任何想法吗? Thank you all in advance!
谢谢大家!
I would use two directives and call one from another. 我将使用两个指令,并从另一个调用。 Further, after compile would call scope method that invokes broadcast.
此外,编译后将调用调用广播的作用域方法。 Something like:
就像是:
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();
}
}
});
as a side note: 附带说明:
I strongly recommend to avoid any DOM update/manipulations in controller. 我强烈建议避免在控制器中进行任何DOM更新/操作。 Use directives.
使用指令。 By this way we can control and track down most issues with call queue.
通过这种方式,我们可以控制和跟踪呼叫队列中的大多数问题。
This is old, but today I solved something similar this way: 这很老,但是今天我用这种方式解决了类似的问题:
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.