AngularJS |范围scope用法详解

2021年3月11日18:14:03 发表评论 687 次浏览

AngularJS中的范围是HTML视图和JavaScript控制器的绑定部分。当你将属性添加到JavaScript控制器中的作用域对象中时, 只有HTML视图可以访问这些属性。 AngulerJS中有两种类型的范围。

范围:Scope中的一些特定功能如下所列

  • HTML视图
  • 当前视图(称为模型)可用的数据
  • 制作/更改/删除/控制数据的JavaScript函数称为Controller。

语法如下:

$scope

范例1:此示例将更清楚地说明范围概念, 此示例包含单个范围。

<!DOCTYPE html>
< html >
  
< head >
     < title >
       AngularJS | Scope
     </ title >
     < script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
     </ script >
</ head >
  
< body >
  
     < div ng-app = "gfg" ng-controller = "control" align = "center" >
  
         < h1 style = "color:green;" >{{organization}}</ h1 >
         < p >A Computer Science Portal</ p >
     </ div >
  
     < script >
         var geeks = angular.module('gfg', []);
         geeks.controller('control', function($scope) {
             $scope.organization = "lsbin";
         });
     </ script >
  
</ body >
  
</ html >

输出如下:

AngularJS |范围1

范例2:在上面的示例中, 在下面的示例中只有一个范围, 你将看到多个范围。

<!DOCTYPE html>
< html >
  
< head >
     < title >
         AngularJS | Scope
     </ title >
     < script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
     </ script >
</ head >
  
< body >
  
     < div ng-app = "gfg" ng-controller = "control" >
  
         < ul >
             < li ng-repeat = "x in names" >{{x}}</ li >
         </ ul >
  
     </ div >
  
     < script >
         var geeks = angular.module('gfg', []);
  
         geeks.controller('control', function($scope) {
             $scope.names = ["Python", "Machine Learning", "Artificial Inteligence"];
         });
     </ script >
  
</ body >
  
</ html >

输出如下:

AngularJS |范围2

rootScope:

如果变量在rootscope和当前作用域中都包含相同的名称, 则控制器或应用程序将使用当前作用域。

语法如下:

$rootScope

范例3:本示例将向你展示如果变量名称在控制器范围和rootscope中相同, 将会发生什么。

<!DOCTYPE html>
< html >
  
< head >
     < title >
         AngularJS | Scope
     </ title >
     < script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
     </ script >
</ head >
  
< body ng-app = "gfg" >
     < h1 >lsbin</ h1 >
     < p >Jack and Jones</ p >
     < h3 >{{relation}}</ h3 >
  
     < div ng-controller = "control" >
  
         < p >Akbar and Antony </ p >
         < h3 >{{relation}}</ h3 >
  
     </ div >
  
     < p >Jay and Viru</ p >
     < h3 >{{relation}}</ h3 >
  
     < script >
         var geeks = angular.module('gfg', []);
         geeks.run(function($rootScope) {
             $rootScope.relation = 'friend';
         });
         geeks.controller('control', function($scope) {
             $scope.relation = "brothers";
         });
     </ script >
  
</ body >
  
</ html >

输出如下:

AngularJS |范围3

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: