指令数据有时在广播后不出现

directive data sometimes does not appear after broadcast

本文关键字:广播 数据 指令      更新时间:2023-09-26

我在Angular中得到了这个恼人的bug,我向指令广播数据,但指令的$on没有接收到它。

因此,我的表根本没有填充,对用户来说看起来很糟糕。

test_results.html(包含一个指令的实例):

<div>
   <h1>Test Results</h1>
   ...
   <results></results>
</div>

resultsCtrl.js控制器:

$timeout(function () {
    $rootScope.$broadcast('show-results', test_session.question_objects);
}, 100);

results.html指令模板(大部分字段被去掉):

<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指令:

scope.$on('show-results', function(event, test_session) {
    setTestSessionData(test_session);
});
...
function setTestSessionData (test_session) {
    scope.questions = test_session;
}

我不知道这到底是什么时候发生的。一开始我以为这是我第一次加载网站的时候,但我已经尝试过了,数据被渲染了。

当您执行$rootScope.$broadcast时,所有通过$scope.$on注册到这些事件的子范围都将捕获该事件。指令作用域也是如此。如果您在事件侦听器中更新模型,它将在视图中更新。

工作柱塞:https://plnkr.co/edit/4iokGsfPH5IqNdecjaGd?p=preview