angularjs $rootScope分发的事件如何能在directive里面响应呢?

    <public-tips></public-tips>

    app.module('demoApp', []).controller('demoController', ['$rootScope', '$scope', function($rootScope, $scope) {
        $rootScope.$broadcast('to-directive', {isShow: true, content: 'hello-directive'});
    })

    app.directive('public-tips', function ($rootScope) {
        return {
            restrict: 'EA',
            template: '<div class="public-tips" ng-show="msg.isShow">{{::msg.content}}</div>',
            link: function (scope, ele, attr) {
                scope.$on('to-directive', function (event, data) {
                    scope.msg = data;
                    console.log(data);
                });
            }
        }
    });

我在$rootScope上分发的事件,但是在directive里面却接受不到?

阅读 3.5k
2 个回答

好吧,鉴于你又改了问题,那我的答案也改一改吧。

首先,如果你期望directive是这样使用的public-tips,那在定义时,应该定义成:app.directive('publicTips'...(注意这里没了横线,而且t大写了)

其次,广播的时机仍然早于接收的定义,所以始终收不到,可以做如下常识:

app.module('demoApp', [])
.controller('demoController', ['$rootScope', '$timeout', function($rootScope, $timeout) {
     $timeout(function(){
        $rootScope.$broadcast('to-directive', {isShow: true, content: 'hello-directive'});
     }, 5000);
       
}]);

如果这次收到了,你就能感受问题所在了吧?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进