<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
里面却接受不到?
为情所困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'...
(注意这里没了横线,而且t
capitalized)
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?
曾经蜡笔没有小新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