search

Home  >  Q&A  >  body text

angular.js - 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: '<p class="public-tips" ng-show="msg.isShow">{{::msg.content}}</p>',
            link: function (scope, ele, attr) {
                scope.$on('to-directive', function (event, data) {
                    scope.msg = data;
                    console.log(data);
                });
            }
        }
    });

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

伊谢尔伦伊谢尔伦2745 days ago557

reply all(2)I'll reply

  • 为情所困

    为情所困2017-05-15 17:03:48

    Okay, since you changed the question again, let me change my answer too.

    First of all, if you expect directive是这样使用的public-tips,那在定义时,应该定义成:app.directive('publicTips'...(注意这里没了横线,而且tcapitalized)

    Secondly, the timing of broadcast is still earlier than the definition of reception, so it is never received. You can make the following common sense:

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

    If you receive it this time, you can feel the problem, right?

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 17:03:48

    Recommended reading this article:

    Communication between angular controllers

    The poster should implement the second method in a similar article

    reply
    0
  • Cancelreply