Angularjs Controller间通信的几种方法

时间:2024-10-04 14:04:08

先说最简单的,适合简单数据

一、使用controller as

<body ng-controller="ParentCtrl as parent">
<input ng-model="parent.name" /> {{parent.name}}
<div ng-controller="ChildCtrl as child">
<input ng-model="child.name" /> {{child.name}} - {{parent.name}}
</div>
</body>

这样parentCtrl中的数据也可以显示在嵌套在其中的childCtrl了

二、使用$rootScope 或 $parent

<body ng-controller="ParentCtrl">
<input ng-model="name" /> {{name}}
<div ng-controller="ChildCtrl">
<input ng-model="name" /> {{name}} - {{$parent.name}}
</div>
</body>

三、使用$broadcast,$emit和$on

  • 从上往下—— $broadcast 把事件广播给所有子controller
  • 从下往上—— $emit 将事件冒泡传递给父controller
  • $on     ——  angularjs的事件注册函数
<div ng-app="app" ng-controller="parentCtrl">
<div ng-controller="childCtrl1">name :
<input ng-model="name" type="text" ng-change="change(name);" />
</div>
<div ng-controller="childCtrl2">Ctr1 name:
<input ng-model="ctrl1Name" />
</div>
</div>
angular.module("app", []).controller("parentCtrl",function ($scope) {
//注册Ctrl1NameChange事件
$scope.$on("Ctrl1NameChange", function (event, msg) {
console.log("parent", msg);
$scope.$broadcast("Ctrl1NameChangeFromParent", msg);
});
}).controller("childCtrl1", function ($scope) {
$scope.change = function (name) {
console.log("childCtrl1", name);
//冒泡Ctrl1NameChange事件,将name传给父级controller
$scope.$emit("Ctrl1NameChange", name);
};
}).controller("childCtrl2", function ($scope) {
//
$scope.$on("Ctrl1NameChangeFromParent",function (event, msg) {
console.log("childCtrl2", msg);
$scope.ctrl1Name = msg;
});
});

jsfiddle链接:http://jsfiddle.net/whitewolf/5JBA7/15/

参看:

  • http://www.cnblogs.com/whitewolf/archive/2013/04/16/3024843.html
  • http://*.com/questions/21287794/angularjs-controller-as-syntax-clarification