为什么没有触发rootscope.on?

时间:2016-06-21 12:53:00

标签: angularjs broadcast emit

我在我的ListController中使用$ scope。$ emit来触发MainController中的$ rootScope。$ on事件(角度1.3):

(function () {
    'use strict';

    angular
        .module('mymodule.faultlist')
        .controller('MainController', ['$rootScope', function ($rootScope) {
            $rootScope.$on('newViewLoaded', function (event, metadata) {
                $rootScope.metadata = metadata;
                console.log('hello metacontroller metadata', metadata);
            });

        }])
        .controller('ListController', ['faultlistservice', 'faultListConstants', '$scope', '$timeout', '$rootScope',
            function (faultlistservice, faultListConstants, $scope, $timeout, $rootScope) {

                $timeout(function () {
                    $scope.$emit('newViewLoaded', {
                        'title': faultListConstants.meta.title,
                        'description': faultListConstants.meta.description
                    });
                }, 100);

            }]);
})();

这就是index.html大致的样子:

.
.
<head ng-controller="MainController">
<div class="container main-content" ui-view >
</div>
..

这不会被触发。我尝试将$ rootScope。$ on块移动到ListController然后$ rootScope。$ on被触发。为什么这不适用于MainController或者是否有更好的方法来实现它?

2 个答案:

答案 0 :(得分:0)

您的代码有效http://plnkr.co/edit/hsl3l6rTJd1SUDgaijCy?p=preview

我认为您的问题可能在于您的ng-app不在html标记上,因此<head ng-controller="MainController">此行不在ngApp中。

答案 1 :(得分:0)

您的代码正常运行http://plnkr.co/edit/nX9KVqY0SZ46Yvf92VAk?p=preview

plunkr显示了如何使用此示例来处理原始代码。这里的标题和描述是要在emit函数内传递的参数,不能是字符串文字

 $scope.$emit('newViewLoaded', {
                        'title': faultListConstants.meta.title,
                        'description': faultListConstants.meta.description
                    })