angular中的scope

  angular.element($0).scope()

什么是scope?

scope是一个refer to the application model的object。它是一个expression的执行上下文context。scopes模仿DOM的层次模型也有层次关系。Scopes可以watch一个expression也可以propagate events。

scope特性

scope提供API $watch来观察模型的变化

scope提供API $apply来传播angular外部世界(比如controller,service,event handler)造成的模型变更到系统中的各个view.

scopes可以嵌套,嵌套的scope要么是child scope或者isolated scope.一个child scope将从parent scope中继承属性,而isolated scope则不会。

scope提供了一个表达式执行的context。比如{{username}}这个表达式,除非给定一个定义了username属性的scope,否则是没有意义的。

scope作为data-model

scope是应用程序的controller和view之间的接口。在template linking阶段,directives建立起$watch expressions on the scope. $watch允许directives被通知到任何属性的变更,这样就允许一个directive来渲染变更过的数据到DOM上。

controller和directive都会引用到scope,但又不完全雷同。这个安排的好处是将controller从directive或者从DOM处隔离开来。这将使得controller和view无关,而这将大大增强应用的可测试性。

<div ng-controller="MyController">
  Your name:
    <input type="text" ng-model="username">
    <button ng-click='sayHello()'>greet</button>
  <hr>
  {{greeting}}
</div>
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
  $scope.username = 'World';

  $scope.sayHello = function() {
    $scope.greeting = 'Hello ' + $scope.username + '!';
  };
}]);

在上面的例子中,MyController给scope对象的username属性赋值为World。然后scope对象将通知和username绑定的input元素,它会将username的值渲染出来。这演示了controller如何能够向scope对象写一个属性。

类似的,controller可以向scope来赋值一个sayHello方法,这个方法将在用户点击greet button时被调用。sayHello方法然后读取username属性并且创建一个greeting属性。这又演示了scope的属性当他们被绑定给input widgets时将随着用户的输入自动更新

逻辑上说:{{greeting}}的渲染包含:

获取template中{{greeting}}的定义所在的DOM节点相关联的scope对象。在这个例子中,这个scope是和传递给MyController相同的scope;

在上面获取到的scope上下文中,Evaluate {{greeting}}表达式,并且将其值赋值给enclosing DOM element的text节点

你可以把scope和它的属性想象成用于渲染视图的数据。scope是所有视图相关的唯一数据源。

另外,从测试的角度说,控制器和视图分离是有必要的,因为它允许我们在不用关心渲染细节的基础上做好测试。

scope层次关系

每一个angular的应用程序只有一个root scope,但是可能有多个子scope

应用程序可以有多个scope,因为一些directive会创建新的子scope。当新的scope被创建时,他们被添加为它的父scope的子孙。这样就创建了一个和他们所相关的DOM平行的树型结构

当angular evaluate {{name}}时,它首先查看和相关html元素相关联的元素是否有name属性。如果没有发现Name属性,它则查找parent scope直到root scope.在javascript中,这个行为被称为prototypical inheriteance,而子scope prototypically inherit from their parents.

https://docs.angularjs.org/guide/scope