控制器的作用
AngularJS同其他JavaScript框架最主要的一个区别就是,控制器并不适合用来执行DOM操
作、格式化或数据操作,以及除存储数据模型之外的状态维护操作。它只是视图和$scope之间的
桥梁。
AngularJS允许在$scope上设置包括对象在内的任何类型的数据,并且在视图中还可以展示
对象的属性。
对象声明及显示如下
1 <!DOCTYPE html> 2 <html ng-app = "myApp"> 3 <head> 4 <title>Simple app</title> 5 </head> 6 <body> 7 <div ng-controller = "MyController"> 8 <h1>{{person}}</h1> 9 and their name: 10 <h2>{{person.name}}</h2> 11 </div> 12 <script type="text/javascript" src = "js/angular.js"></script> 13 <script type="text/javascript" src = "js/app.js"> 14 </script> 15 </body> 16 </html> 17 18 var myApp = angular.module("myApp", []) 19 20 myApp.controller('MyController', function($scope) { 21 $scope.person = { 22 name: 'Ari' 23 }; 24 });
控制器的嵌套
若controller2在div中置于controller1内部,则controller1就是controller2的父级,则controller2可使用controller的对象,示例如下
1 <!DOCTYPE html> 2 <html ng-app = "myApp"> 3 <head> 4 <title>Simple app</title> 5 </head> 6 <body> 7 <div ng-controller = "ParentController"> 8 <div ng-controller = "ChildController"> 9 <a ng-click = "sayHello()">Say hello</a> 10 </div> 11 {{person}} 12 </div> 13 <script type="text/javascript" src = "js/angular.js"></script> 14 <script type="text/javascript" src = "js/app.js"> 15 </script> 16 </body> 17 </html> 18 19 var myApp = angular.module("myApp", []) 20 21 myApp.controller('ParentController', function($scope) { 22 $scope.person = { 23 greeted: false 24 }; 25 }); 26 myApp.controller('ChildController', function($scope) { 27 $scope.sayHello = function() { 28 $scope.person.greeted = true; 29 $scope.person.name = 'Ari' 30 }; 31 })