1. 程式人生 > >Angular——作用域

Angular——作用域

scope 存在 function func 標簽 title utf mode script

基本介紹

應用App是無法嵌套的,但是controller是可以嵌套的,每個controller都會對應一個模型(model)也就是$scope對象,不同層級的controller下的$scope遍產生了作用域

基本使用

根作用域:作用範圍是整個應用(ng-app所在標簽中)都是可以被訪問的,使用的時候可以借助ng-init創建屬性

子作用域:存在於controller中,嵌套中在其他controller中的controller可以訪問,上層的屬性

<!DOCTYPE html>
<html lang="en" ng-app="App" ng-init="name=‘祖宗‘"
> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../libs/angular.min.js"></script> </head> <body> <div ng-controller="ParentController"> <div ng-controller="ChildController"> <span>{{name}}</span
> </div> </div> <script> var App = angular.module(App, []); App.controller(ParentController, [$scope, function ($scope) { // $scope.name = ‘父母‘; }]); App.controller(ChildController, [$scope, function ($scope) { // $scope.name = ‘兒子‘; }]);
// ng-init="name=‘祖宗‘"==》相當於創建了一個全局變量 $scope.name=‘祖宗‘ // 子作用域可以訪問父作用域 </script> </body> </html>

Angular——作用域