AngularJS 作用域

作者 : 慕源网 本文共1848个字,预计阅读时间需要5分钟 发布时间: 2022-04-29 共265人阅读

AngularJS 作用域AngularJS 中的作用域是 HTML 视图和 JavaScript 控制器的纽带。当您将属性添加到 JavaScript 控制器中的Scope对象时,HTML 视图才能访问这些属性。AngularJS 中有两种类型的 Scope。 

  • $Scope
  • $rootScope

Scope:下面列出了Scope中的几个具体功能

  • View(视图)
  • Model(模型),可用于当前视图的数据
  • Controller(控制器), 即 JavaScript 函数,可以添加或修改属性。

语法:

$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 = "GeeksforGeeks";
		});
	</script>

</body>

</html>

输出:

示例 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 Intelligence"];
		});
	</script>

</body>

</html>				

输出:

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

语法:

$rootScope

示例 3:此示例将向您展示,如果控制器的作用域和根作用域中的变量名称相同,将会发生什么情况。

<!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>GeeksforGeeks</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 作用域

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录