angular.js - angularjs $rootScope分发的事件如何能在directive里面响应呢?
伊谢尔伦
伊谢尔伦 2017-05-15 17:01:48
0
2
528
    <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里面却接受不到?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
为情所困

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?

曾经蜡笔没有小新

Recommended reading this article:

Communication between angular controllers

The poster should implement the second method in a similar article

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!