作用域是一個特殊的JavaScript對象,用于將控制器與視圖連接起來。范圍包含模型數(shù)據(jù)。在控制器中,通過 $scope 對象訪問模型數(shù)據(jù)。
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
</script>上例中考慮了以下要點-
$scope在其構(gòu)造函數(shù)定義期間作為第一個參數(shù)傳遞給控制器。
$scope.message和$scope.type是HTML頁面中使用的模型。
我們?yōu)閼?yīng)用程序模塊中反映的模型分配值,該模塊的控制器為shapeController。
我們可以在$scope中定義函數(shù)。
scope(作用域)是特定于控制器的。如果我們定義了嵌套控制器,那么子控制器將繼承其父控制器的范圍。
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
</script>上例中考慮了以下要點-
我們在shapeController中為模型分配值。
我們在名為circleController的子控制器中覆蓋消息。當在名為circleController的控制器模塊中使用message時,將使用覆蓋的消息。
以下示例顯示了上述所有指令的使用。
<html>
<head>
<title>Angular JS Forms</title>
</head>
<body>
<h2>AngularJS Scope(作用域)</h2>
<div ng-app = "mainApp" ng-controller = "shapeController">
<p>{{message}} <br/> {{type}} </p>
<div ng-controller = "circleController">
<p>{{message}} <br/> {{type}} </p>
</div>
<div ng-controller = "squareController">
<p>{{message}} <br/> {{type}} </p>
</div>
</div>
<script src = "https://cdn.staticfile.org/angular.js/1.3.14/angular.min.js">
</script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "形狀控制器";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "圓圈控制器";
});
mainApp.controller("squareController", function($scope) {
$scope.message = "方形控制器";
$scope.type = "Square";
});
</script>
</body>
</html>測試看看?/?輸出結(jié)果

在網(wǎng)絡(luò)瀏覽器中打開文件testAngularJS.htm并查看結(jié)果。