指令数据有时在广播后不出现 [英] directive data sometimes does not appear after broadcast
问题描述
我在Angular中遇到了一个烦人的bug,我在其中将数据广播到指令,但是指令的 $ on
没收到它.
I'm getting this annoying bug with Angular where I broadcast data to a directive but the directive's $on
doesn't receive it.
因此,我的表根本没有填充,并且对用户来说很糟糕.
Therefore, my table doesn't populate at all and looks terrible to users.
test_results.html(包含指令的实例):
test_results.html (contains an instance of the directive):
<div>
<h1>Test Results</h1>
...
<results></results>
</div>
resultsCtrl.js控制器:
resultsCtrl.js controller:
$timeout(function () {
$rootScope.$broadcast('show-results', test_session.question_objects);
}, 100);
results.html指令模板(去除了大部分字段):
results.html directive template (most fields stripped out):
<div class="results">
<table class="table table-bordered table-striped">
<thead>
<tr>
<td ng-if="average_times && !$root.is_mobile">
<span ng-click="sortType = 'question.average_timing'; sortReverse = !sortReverse">
Avg. Time
</span>
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="q in questions | orderBy:sortType:sortReverse | filter:searchQuestions track by $index">
<td ng-if="q.average_timing && !$root.is_mobile" ng-click="$root.openDirections('question', q)">{{ q.average_timing }}</td>
</tr>
</tbody>
</table>
</div>
results.js指令:
results.js directive:
scope.$on('show-results', function(event, test_session) {
setTestSessionData(test_session);
});
...
function setTestSessionData (test_session) {
scope.questions = test_session;
}
我无法弄清楚什么时候会发生这种情况.起初我以为是第一次加载该站点,但是从那时起我就尝试过了,并呈现了数据.
I cannot figure out when exactly this happens. At first I thought it's when I load the site for the first time, but I've tried that since and the data is rendered.
推荐答案
每当您执行 $ rootScope.$ broadcast
时,所有通过 $ scope注册到这些事件的子作用域.$ on
将捕获该事件.指令范围也一样.如果您在事件监听器中更新模型,它将在视图中更新.
Whenever you do a $rootScope.$broadcast
all the child scopes who have registered to those events via $scope.$on
will catch the event. Same goes with directive scope also. If you update the model in the event listener , it will be updated in the view.
工作勤奋的人: https://plnkr.co/edit/4iokGsfPH5IqNdecjaGd?p=preview
这篇关于指令数据有时在广播后不出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!