一、什么是Scope?
scope(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope)是一个指向应用model的object。它也是expression(http://www.cnblogs.com/lcllao/archive/2012/09/16/2687162.html)的执行上下文。scope被放置于一个类似应用的DOM结构的层次结构中。scope可以监测(watch,$watch)expression和传播事件。
二、scope的特性
三、Scope as Data-Model(scope作为数据模型)
scope是在应用controller与view之间的纽带。在模版linking(http://www.cnblogs.com/lcllao/archive/2012/09/04/2669802.html)的阶段,directive(http://www.cnblogs.com/lcllao/archive/2012/09/09/2677190.html)在scope中设置$watch表达式。$watch让directive能够得知属性的变化,使得directive将更新后的值渲染到DOM中。
controller和directive两者都与scope有引用,但它们两者之间没有(引用)(Both controllers and directives have reference to the scope, but not to each other)。这样的安排,将controller从directive和DOM中隔离开来。这是一个重要的地方,因为它让controller与view是隔离的,极大地提升了应用的可测试性(greatly improves the testing story of the applications)。
<!DOCTYPE HTML><html lang="zh-cn" ng-app><head> <meta charset="UTF-8"> <title>data-model</title> <style type="text/css"> .ng-cloak { display: none; } </style></head><body class="ng-cloak"><div ng-controller="MyController"> 你的名字: <input type="text" ng-model="username"/> <button ng-click="sayHello()">欢迎</button> <hr/> {{greeting}}</div><script src="../angular-1.0.1.js" type="text/javascript"></script><script type="text/javascript"> function MyController($scope) { $scope.username = "My Little Dada"; $scope.sayHello = function() { $scope.greeting = "Hello~" + $scope.username + "!"; }; }</script></body></html>
在上面的例子中我们可以注意到MyController以”My Little Dada”对scope中的username属性进行赋值。然后,scope通知input进行赋值,将username的值预先填入input中。这展示了controller如何做才能够写入数据到scope中。
新闻热点
疑难解答
图片精选