Angular. js Scope scope '@' '=' ''Instance Explanation

  • 2021-07-24 09:58:45
  • OfStack

What is scope

In AngularJS, the scope is an object pointing to the application model, which is the execution environment of the expression. Scope has a hierarchy, which is almost identical to the corresponding DOM. Scope can monitor expressions and pass events.

In the HTML code, once an ng-app instruction is defined, then a scope is generated. The scope generated by ng-app is special, it is a root scope ($rootScope), which is the topmost level of all other $Scope.

Except for ng-app instructions, which can generate one scope, other instructions such as ng-controller, ng-repeat, etc. will generate one or more scopes. In addition, you can create a scope using the factory method for creating scopes provided by AngularJS. Each of these scopes has its own inheritance context, and the root scope is $rootScope.

After generating a scope, when writing AngularJS code, the $scope object represents the data entity of this scope. We can define various data types in $scope, and then let HTML access this variable directly in HTML in the form of {{variable name}}.

The following is an example code to introduce the scope scope '@', '=', 'of angular. js & '


<!doctype html> 
<html ng-app='myApp'> 
<head> 
</head> 
<body> 
    <script src="http://cdn.bootcss.com/angular.js/1.4.6/angular.js"></script>
    <script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.js"></script>
    <div ng-controller="listCtrl" ng-app="myApp"> 
          <input type="text" ng-model="color"> 
          <!-- <span kid hd-color="color"></span> --> <!--@ Is a single data binding, hd-color="{{color}}" Scope isolation, in view In the template " {{}} The form of "; = Two-way binding, hd-color="color", In view Appears directly in the form of attributes in -->
          <div kid color="callback()"></div>
    </div>
<script type="text/javascript">
          var myApp=angular.module('myApp',[]); 
          myApp.controller('listCtrl',function($scope){ 
                $scope.color="red"; 
                $scope.callback=function(){
                      return 'a web developer !';
                }
          }); 
          myApp.directive('kid',function(){ 
                return { 
                      restrict:'AE', 
                      //template:'<div style="color:{{color}}">@ Learning of symbols </div>' , 
                      template:'<h1>{{color()}}</h1>', 
                      scope:{ /*color:"=hdColor"*//* "@hdColor" */color:'&'} // Pass & Property name to call the function of the controller 
                } 
          }); 
</script>
</div> 
</body>
</html>

Related articles: