问题描述
<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 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里面却接受不到?
问题解答
回答1:好吧,鉴于你又改了问题,那我的答案也改一改吧。
首先,如果你期望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); }]);
如果这次收到了,你就能感受问题所在了吧?
回答2:推荐阅读这篇文章:
angular 控制器之间的通信
楼主应该是要实现类似文章中的第二种方式