控制器在AngularJS中的作用是增强视图
创建方法
var app = angular.module('app', []);
app.controller('FirstController', function($scope) {
$scope.message = "hello";
$scope.add = function(amount) { $scope.counter += amount; };
});
控制器的嵌套(作用域包含作用域)
对于ng-app所处的层级来说,它的父级作用域是 $rootScope
默认情况下,AngularJS在当前作用域中找不到某个属性时,便会在父级作用域中查找,如何找不到会顺着父级作用域一直身上查找,直到抵达$rootScope。
Example
app.controller('ParentController', function($scope) {
$scope.person = {greeted: false};
});
app.controller('ChildController', function($scope) {
$scope.sayHello = function() {
$scope.person.name = 'Ari Lerner';
};
});
<div ng-controller="ParentController">
<div ng-controller="ChildController">
<a ng-click="sayHello()">Say hello</a>
</div>
{{ person }}
</div>
结果
{"greeted": false,"name":"Ari Lerner"}