首页 > 语言 > JavaScript > 正文

AngularJs Scope详解及示例代码

2024-05-06 14:52:11
字体:
来源:转载
供稿:网友

一、什么是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提供$watch API(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope#$watch),用于监测model的变化。 scope提供$apply API(http://code.angularjs.org/1.0.2/docs/api/ng.$rootScope.Scope#$apply),在“Angular realm”(controller、server、angular event handler)之外,从系统到视图传播任何model的变化。 scope可以在提供到被共享的model属性的访问的时候,被嵌入到独立的应用组件中。scope通过(原型),从parent scope中继承属性。 scope在expression求值之时提供上下文环境。例如,{{username}}表达式是无意义的,除非它与一个特定的定义了”username”属性的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中。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选