【发布时间】: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}。