我正在尝试从一个控制器生成广播事件并再听一个控制器。但是结果没有显示在DOM上,尽管没有错误。而且当我从两个控制器显示正常的$ scope变量时,它正在工作。只是广播和播放不起作用,因为没有错误,所以我不调试
oneApp.controller("twoController",["$log","$scope","$rootScope",function($log,$scope,$rootScope){
var str ="sent from twoController ";
$scope.hey = 215;
$rootScope.$broadcast("hey",str);
}])
oneApp.controller("twoChildController", ["$log","$scope","$rootScope",function($log,$scope,$rootScope){
//var str ="sent from twoController ";
//$scope.display = str;
$scope.$on("hey",function(event,str){
$scope.display = str;
});
}])
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
在这种情况下,controller1首先启动,然后启动controller2。当controller1发起广播事件时,控制器2尚未启动,即$尚未注册。你可以使用$ timeout。
var app = angular.module("myApp",[]);
//controllers declaration
app.controller('myCtrl1',function($scope, $rootScope, $timeout){
$scope.name = "Roger";
$timeout(function(){
$rootScope.$broadcast('hey',$scope.name);
});
});
app.controller('myCtrl2',function($scope, $rootScope){
$scope.$on('hey',function(event,name){
$scope.name=name;
});
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div class="div1" ng-controller="myCtrl1">
<span>myCtrl1 : {{name}}</span>
</div>
<div class="div2" ng-controller="myCtrl2">
<span>myCtrl2 : {{name}}</span>
</div>
</body>
&#13;
答案 1 :(得分:0)
尝试以某种方式:
在某个主控制器中定义所有广播,例如:
$rootScope.broadcast.actions = {
hey : 'hey'
//all broadcast
}
广播发送:
$rootScope.$broadcast($rootScope.broadcast.actions.hey,{str});
广播接收:
$scope.$on($rootScope.broadcast.actions.hey, function (event,str){
$scope.display = str;
});