✔ AngularJS Scope
> scope is the binding part between the HTML (view) and the JavaScript (controller)
> scope is an object with the available properties and methods
> scope is available for both the view and the controller
1. How to Use the Scope
> when you make a controller in AngularJS, you pass the $scope object as an argument
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
: when adding properties to the $scope object in the controller, the viewer gets access to these properties.
: in the view, you do not use the prefix $scope, you just refer to a property name, like {{carname}}.
2. Understanding the Scope
> If we consider an AngularJS application to consist of:
- View, which is the HTML
- Model, which is the data available for the current view.
- Controller, which is the JavaScript function that makes/changes/removes/controls the data
Then the scope is the Model.
> The scope is a Javascript object which properties and methods, which are available for both the view and the controller.
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>My name is {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
3. Know Your Scope
> It is important to know which scope you are dealing with, at any time.
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Kim", "Lee", "Park"];
});
</script>
: when dealing with the ng-repeat directive, each repetition has access to the current repetition object
= each <li> element has access to the current repetition object, in this case a string, which is referred to by using x.
4. Root Scope
> All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive
> rootScope is available in the entire application
> If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.
<body ng-app="myApp">
<p>The rootScope's favorite color:</p>
<h1>{{color}}</h1>
<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color:</p>
<h1>{{color}}</h1>
</div>
<p>The rootScope's favorite color is still:</p>
<h1>{{color}}</h1>
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
$scope.color = "red";
});
</script>
</body>
'IT' 카테고리의 다른 글
AngularJS #11 - Services (0) | 2021.12.26 |
---|---|
AngularJS #10 - Filters (0) | 2021.12.26 |
AngularJS #8 - Controllers (0) | 2021.12.21 |
AngularJS #7 - Data Binding (0) | 2021.12.21 |
AngularJS #6 - ng-model Directive (0) | 2021.12.19 |