Angularjs 我在使用“$rootScope.$broadcast”和“$on”时遇到问题

Angularjs 我在使用“$rootScope.$broadcast”和“$on”时遇到问题,angularjs,angularjs-scope,Angularjs,Angularjs Scope,我有一个关于使用$rootScope.$broadcast和$scope.$on的问题 我有一个单模块和两个控制器控制器1和控制器2 var app = angular.module("app",[]); app.controller("Controller1",function ($scope,$rootScope){ $scope.$on("msgUpdated",function (event,data){ console.log(data.message); }) app.con

我有一个关于使用$rootScope.$broadcast和$scope.$on的问题

我有一个单模块和两个控制器控制器1和控制器2

    var app = angular.module("app",[]);
app.controller("Controller1",function ($scope,$rootScope){
$scope.$on("msgUpdated",function (event,data){
console.log(data.message);
})
app.controller("Controller2",function ($scope,$rootScope){
$scope.msg = "Hi!";
$rootScope.$broadcast("msgUpdated",{message:msg});
});
以上是我的代码

问题是我的控制器1的$scope.$on不工作。 为什么?我不明白。 还有,我怎样才能把它固定在消防控制器1的$scope.$on上

<body ng-app="app">
    <div ng-controller="Controller1">
        <h1>{{msg1}}</h1>
        <input ng-model="test" ng-blur="sendMsg()"/>
    </div>
    <div ng-controller="Controller2">
        <h1>{{msg2}}</h1>
        <input ng-model="test" ng-blur="sendMsg()"/>
    </div>
</body>

var app = angular.module('app',[])
.controller('Controller1',['$rootScope','$scope',function($rootScope,$scope){
    $scope.msg1 = "Start";
    $scope.sendMsg = function() {
        $rootScope.$emit('msg',$scope.test);
    };
    var cleanup = $rootScope.$on('msg2', function (event,data) {
        $scope.msg1 = data;
    });

    $scope.$on('$destroy', cleanup);
}])
.controller('Controller2',['$rootScope','$scope',function($rootScope,$scope){
    $scope.msg2 = "Start2";
        $scope.sendMsg = function() {
        $rootScope.$emit('msg2',$scope.test);
    };
    var cleanup = $rootScope.$on('msg', function (event,data) {
        $scope.msg2 = data;
    });

    $scope.$on('$destroy', cleanup);
}]);
这是小提琴手: 我总是使用$rootScope.$emit和clean


如何以及在何处将这些控制器绑定到HTML?我有两个指令。它们同时共享相同的$rootScope?指令1的对象是return{templateUrl:index1.HTML controller:Controller1},指令2的对象是return{templateUrl:index2.HTML controller:Controller2}。对我适用。但是我在您的代码中看到了两个大问题,如果您打开开发人员控制台,您应该看到这两个问题:1您没有关闭第一个控制器的},第二个msg在第二个控制器中未定义,它应该是{message:$scope.msg}。谢谢!它真的帮助了我!!