AngularJS Scope
Scope is the link between HTML (view) and JavaScript (controller).
Scope is an object with available methods and properties.
Scope can be applied to views and controllers.
How to Use Scope
When you create a controller in AngularJS, you can$scopepass the object as a parameter:
AngularJS Example
Properties in the controller correspond to properties on the view:
<h1>{{carname}}</h1>
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
Try it »
When adding in the controller$scopethe object, the view (HTML) can obtain these properties.
In the view, you do not need to add$scopeprefix, just add the property name, such as:{{carname}}。
Scope Overview
An AngularJS application consists of the following:
- View, i.e., HTML.
- Model, the data available in the current view.
- Controller, i.e., a JavaScript function that can add or modify properties.
scope is the model.
scope is a JavaScript object with properties and methods, and these properties and methods can be used in views and controllers.
AngularJS Example
If you modify the view, the model and controller will update accordingly.
Try it »
Scope Range
It is very important to understand the scope you are currently using.
In the above two examples, there is only one scope, so it is relatively simple, but in large projects, there are multiple scopes in the HTML DOM, and you need to know which scope is the one you are using.
AngularJS Example
When we useng-repeatthe directive, each repeated item accesses the current repeated object:
<ul>
<li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
Try it »
Each<li>element can access the current repeated object, which here corresponds to a string, and uses the variablexto represent it.
Root Scope
All applications have a$rootScope, which can act onng-appall HTML elements contained by the directive.
$rootScopeIt can act on the entire application. It is a bridge between scopes in various controllers. Values defined with rootscope can be used in each controller.
AngularJS Example
When creating a controller, pass $rootScope as a parameter, and it can be used in the application:
<h1>{{lastname}}Family members:</h1>
<ul>
<li ng-repeat="x in names">{{x}} {{lastname}}</li>
</ul>
</div>
<script>
app.controller('myCtrl', function($scope, $rootScope) {
$scope.names = ["Emil", "Tobias", "Linus"];
$rootScope.lastname = "Refsnes";
});
Try it »