Let me talk about the most simple, suitable for simple data
First, use the 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>
Such data may also be displayed in parentCtrl childCtrl nested therein in the
Second, use $ rootScope or $ parent
<body ng-controller="ParentCtrl"> <input ng-model="name" /> {{name}} <div ng-controller="ChildCtrl"> <input ng-model="name" /> {{name}} - {{$parent.name}} </div> </body>
Third, the use of $ broadcast, $ emit and $ on
- From top to bottom - $ Broadcast the event is broadcast to all sub-controller
- From the bottom up - $ EMIT will be passed to the parent controller event bubbling
- ON $ - AngularJS event registration function
<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);
// bubble Ctrl1NameChange event, the name passed to the parent controller $scope.$emit("Ctrl1NameChange", name); }; }).controller("childCtrl2", function ($scope) { // $scope.$on("Ctrl1NameChangeFromParent",function (event, msg) { console.log("childCtrl2", msg); $scope.ctrl1Name = msg; }); });
jsfiddle link: http://jsfiddle.net/whitewolf/5JBA7/15/
See also:
- http://www.cnblogs.com/whitewolf/archive/2013/04/16/3024843.html
- http://stackoverflow.com/questions/21287794/angularjs-controller-as-syntax-clarification
Reproduced in: https: //www.cnblogs.com/JoannaQ/p/5053680.html