1.首先一段相互有嵌套控制器的html
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div ng-app="myApp"> <div ng-controller="firstController"> <input type="text" ng-model="name"> <input type="text" ng-model="age"> {{ name }} {{ age }} <div ng-controller="secondController"> <input type="text" ng-model="name"> {{ name }} <div ng-controller="thirdController"> <input type="text" ng-model="name"> {{ name }} </div> </div> </div> </div> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script src="app/index.js"></script> </body> </html>
2.如上,firstController中包含着 senondController,senondController中又包含着thirdController
var app=angular.module('myApp',[]); app.controller("firstController",function($scope){ $scope.name="张三丰"; $scope.age=20; }); app.controller("secondController",function ($scope) { }); app.controller('thirdController',function($scope){ });
我们仅在最外层的 firstController中定义了模型 name 和 age,而页面上我们要在secondController和thirdController中也展示name ,运行结果如下:
发现,secondController和thirdController自身都没有name,于是向自己上层的控制器寻找name变量,故展示了上层控制器的变量值
3.在页面上修改firstController中的model值,则secondController和thirdController的内值同步变化
4.在页面上修改secondController内的文本框内的值,只有thirdController内的值变化,因为此时secondController内新建了自己的name模型,thirdController内向上寻找一层就找到了这个新建的name模型
5.同理,再修改thirdController内文本框的值,则在thirdController中新建了它自己的name模型,此时三者的name就互不影响了
原文链接:https://www.f2er.com/angularjs/148748.html