IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    AngularJS笔记:$scope和this

    axiu发表于 2016-03-15 10:07:38
    love 0

    近来感觉东西越积越多,有些以前用过的小知识到现在都想不起来了,所以决定偶尔做个小笔记,虽然索性就放博客上了。

    从若干的基础教程来看,scope是angular controller里数据绑定的关键,不管是从controller到view还是相反。

    用scope,可以轻易声明一个可以到处使用的变量,例如:

    app.controller('MainCtrl', function ($scope) {
      $scope.title = 'Some title';
    });

    而使用this,则可以声明一个在controller作用域内使用的变量,类似java的类当中public的局部变量。

    app.controller('MainCtrl', function () {
      this.title = 'Some title';
    });

    从“对象”的角度来看,scope的写法像是声明了一个全局变量(就是怎么用怎么错的全局变量),然后不停的赋值、修改元素、删除元素。

    this配合Controller As

    当有了Controller As这个东西的时候,this就变的很好用。可以轻易搞清楚各个controller的层级关系,调用到合适的变量。这一点在嵌套的时候尤其明显。举个栗子

    使用this之前:

    <div ng-controller="MainCtrl">
      {{ title }}
      <div ng-controller="ChildCtrl">
        Scope title: {{ title }}
        Parent title: {{ $parent.title }}
        <div ng-controller="GrandsonCtrl">
          Scope title: {{ title }}
          Parent title: {{ $parent.title }}
          Parent parent title: {{ $parent.$parent.title }}
        </div>
      </div>
    </div>

    使用了this之后:

    <div ng-controller="MainCtrl as parent">
      {{ parent.title }}
      <div ng-controller="ChildCtrl as child">
        Scope title: {{ child.title }}
        Parent title: {{ parent.title }}
        <div ng-controller="GrandsonCtrl as grandson">
          Scope title: {{ grandson.title }}
          Parent title: {{ child.title }}
          Parent parent title: {{ parent.title }}
        </div>
      </div>
    </div>

    其实如果平时就嵌套两层以内,使用起来差别也不是很大。有一点区别就是,要使用scope,必须为controller注入$scope。而使用Controller As和this则不必,直接使用即可。所以在某种程度上,你可以决定何时需要使用scope。

    这里有个例子。

    转载请注明来源:AngularJS笔记:$scope和this
    本文链接地址:http://axiu.me/coding/angularjs-scope-and-this/


沪ICP备19023445号-2号
友情链接