【问题标题】:Why is rootscope.on not triggered?为什么 rootscope.on 没有被触发?
【发布时间】:2016-06-21 12:52:59
【问题描述】:

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

(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 不起作用,或者有更好的方法来实现它?

【问题讨论】:

  • @TheHeadRush 好像是同一个问题!!!
  • 如果 ListController 是 MainController 的父级吗?可以分享一下 HTML 吗?
  • 是 MainController 定义在顶部,即定义在 head 标签中。 ListController 位于 ui-view (ui-router) 中。 MainController 未在 stateprovider 中定义。
  • 噢!我发布了错误的链接。感谢您指出了这一点。 stackoverflow.com/questions/26752030/…
  • @The Head Rush 如果 $scope.emit 上升,那么我假设 $rootScope.$on 会根据链接触发?

标签: angularjs broadcast emit


【解决方案1】:

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

我认为您的问题可能在于您的 ng-app 不在 html 标签上,所以&lt;head ng-controller="MainController"&gt; 这一行在 ngApp 之外。

【讨论】:

    【解决方案2】:

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

    plunkr 展示了如何使用此示例来处理原始代码。这里的 title 和 description 是要在 emit 函数中传递的参数,不能是字符串字面量

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

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      相关资源
      最近更新 更多