【问题标题】:I have a trouble about using "$rootScope.$broadcast" and "$on"我在使用“$rootScope.$broadcast”和“$on”时遇到了麻烦
【发布时间】:2015-01-30 00:24:23
【问题描述】:

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

我有一个模块和两个控制器(Controller1 和 Controller2)。

    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});
});

以上是我的代码。

问题是我的 Controller1 的 $scope.$on 不工作。 为什么?我不明白。 并且,如何修复它以触发 Controller1 的 $scope.$on ?

【问题讨论】:

  • 如何以及在何处将这些控制器绑定到 HTML?
  • 我有两个指令。
  • 他们同时共享同一个$rootScope
  • 指令 1 的对象是 return { templateUrl:"index1.html" controller:"Controller1" },指令 2 的对象是 return { templateUrl:"index2.html" controller:"Controller2"}。跨度>
  • 为我工作。 jsfiddle.net/8a77t445 但我在您的代码中看到两个大问题(如果您打开开发者控制台,您应该已经看到这两个问题):(1)您没有关闭第一个控制器的 }),第二个 msg 在第二个中未定义控制器,应该是{message: $scope.msg}

标签: angularjs angularjs-scope


【解决方案1】:
<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 并进行清理。

http://jsfiddle.net/hbqsbLyg/

【讨论】:

  • 谢谢!它真的帮助了我!
猜你喜欢
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-16
  • 2017-09-12
  • 2011-08-28
  • 2022-01-05
相关资源
最近更新 更多