码迷,mamicode.com
首页 > 其他好文 > 详细

Angular this vs $scope

时间:2016-12-21 23:56:47      阅读:428      评论:0      收藏:0      [点我收藏+]

标签:filter   函数   ddp   注入   状态   repeat   because   输出   default   

this vs $scope

------------------------------------------------------------------------------ 

‘this‘ vs $scope in AngularJS controllers

How does this and $scope work in AngularJS controllers?

Short answer:

  • this
    • When the controller constructor function is called, this is the controller.(当控制器构造函数被“调用”时,this就是控制器函数)
    • When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!)(this可能是也可不能不是$scope) be the $scope that the function is defined on. So, inside the function, this and $scope may not be the same.
  • $scope
    • Every controller has an associated $scope object(每个控制器都有一个与其相关联的$scope).
    • A controller (constructor) function is responsible for setting model properties and functions/behaviour on its associated $scope.
    • Only methods defined on this $scope object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from ng-click, filters, etc.

Long answer:

A controller function is a JavaScript constructor function.(控制器函数就是一个普普通通地构造器函数)

When the constructor function executes (e.g., when a view loads), this (i.e., the "function context") is set to the controller object. So in the "tabs" controller constructor function, when the addPane function is created

this.addPane = function(pane) { ... }

it is created on the controller object, not on $scope. Views cannot see the addPane function -- they only have access to functions defined on $scope. In other words, in the HTML, this won‘t work:

<a ng-click="addPane(newPane)">won‘t work</a>

After the "tabs" controller constructor function executes, we have the following:

技术分享

 

The dashed black line indicates prototypal inheritance -- an isolate scope prototypically inherits from Scope. (It does not prototypically inherit from the scope in effect where the directive was encountered in the HTML.)

Now, the pane directive‘s link function wants to communicate with the tabs directive (which really means it needs to affect the tabs isolate $scope in some way). Events could be used, but another mechanism is to have the pane directive require the tabs controller. (There appears to be no mechanism for the pane directive to require the tabs $scope.)

So, this begs the question: if we only have access to the tabs controller, how do we get access to the tabs isolate $scope (which is what we really want)?

Well, the red dotted line is the answer. The addPane() function‘s "scope" (I‘m referring to JavaScript‘s function scope/closures here) gives the function access to the tabs isolate $scope. I.e., addPane() has access to the "tabs IsolateScope" in the diagram above because of a closure that was created when addPane() was defined. (If we instead defined addPane() on the tabs $scope object, the pane directive would not have access to this function, and hence it would have no way to communicate with the tabs $scope.)

To answer the other part of your question: how does $scope work in controllers?:

Within functions defined on $scope, this is set to "the $scope in effect where/when the function was called". Suppose we have the following HTML:

<div ng-controller="ParentCtrl">
   <a ng-click="logThisAndScope()">log "this" and $scope</a> - parent scope
   <div ng-controller="ChildCtrl">
      <a ng-click="logThisAndScope()">log "this" and $scope</a> - child scope
   </div>
</div>

And the ParentCtrl (Solely) has

$scope.logThisAndScope = function() {
    console.log(this, $scope)
}

Clicking the first link will show that this and $scope are the same, since "the scope in effect when the function was called" is the scope associated with the ParentCtrl.

Clicking the second link will reveal this and $scope are not the same, since "the scope in effect when the function was called" is the scope associated with the ChildCtrl. So here, this is set to ChildCtrl‘s $scope. Inside the method, $scope is still the ParentCtrl‘s $scope(点击子控制器时,this指向了子控制器(this的指向问题),$scope仍旧指向了父控制器).

I try to not use this inside of a function defined on $scope, as it becomes confusing which $scope is being affected, especially considering that ng-repeat, ng-include, ng-switch, and directives can all create their own child scopes.

--------------------------------------------------------------------------

Angular this vs $scope     

最近在Angular项目中遇到关于controller内使用$scope&this 暴露数据的问题,下面来分析一下:

“controller as” 是Angular在1.2版本后新增的语法,我将从引用方式,作用范围,对象对比三个方面做两者的比较:

一、引用方式:

 1) $scope 只需要在注入中声明,后面就可以直接在附加数据对象:

            controller:            

                function ACtrl($scope) {

                    $scope.test = "一个例子"; //在$scope对象中加入test

                }

            html:

                <div ng-controller="ACtrl">

                    {{test}}

                </div>

 2) this 则采用了controller as(需要版本为ng 1.2+)写法:

          controller:

                function BCtrl() {

                    var vm = this;

                    this.test = "一个例子"; //在this对象中加入test

                }

            html:        

                <!-- vm为自己为当前控制器作的一个简略记号,也可以写作 BCtrl as b,

                     后面变量便可以在b中引出 如b.test -->

                <div ng-controller="BCtrl as vm">

                    {{vm.test}}

                </div>

二、作用范围:

        1) $scope 中的变量或数据对象我们可以全部拿到,并且上级控制器中的变量也可以在下级控制器中被获取到:

            controller:

                function ParentCtrl($scope) {

                    $scope.test = "测试";

                    

                    $scope.cover ="覆盖测试";

                }

                function ChildCtrl($scope) {

                    $scope.cover ="子覆盖测试";

                    var test = $scope.test; //“测试”

                }

            html:

                <div ng-controller="ParentCtrl">

                    <p>Parent-test : {{test}}</p>

                    <p>Parent-cover : {{cover}}</p>

                    <div ng-controller="ChildCtrl">

                        <p>Child-test : {{test}}</p>

                        <p>Child-cover : {{cover}}</p>

                    </div>

                </div>    

            我在父控制器ParentCtrl中声明的test变量并未在子控制器ChildCtrl中做声明,而在ChildCtrl作用范围内的Child-test 中,test却输出了”测试”;基于此我再做了一次覆盖测试,检测结果显示,当父子控制器同时存在相同的变量时, 父子控制器各自范围内的值不会被覆盖;

         

        2) this 中的变量则只适用于当前控制器:

            controller:

                function ParentCtrl($scope) {

                    var vm = this;

                    

                    vm.test = "测试";

                    vm.cover ="覆盖测试";

                }

                function ChildCtrl($scope) {

                    var vm = this;

                    

                    vm.cover ="子覆盖测试";

                }

            html:

                <div ng-controller="ParentCtrl as parent">

                    <p>Parent-test : {{parent.test}}</p>

                    <p>Parent-cover : {{parent.cover}}</p>

                    <div ng-controller="ChildCtrl as child">

                        <p>Child-test : {{child.test}}</p>

                        <p>Child-cover : {{child.cover}}</p>

                    </div>

                    <div ng-controller="ChildCtrl as parent">

                        <p>Child-test : {{parent.test}}</p>

                        <p>Child-cover : {{parent.cover}}</p>

                    </div>

                </div>

    在使用this的时候,各层级变量的命名空间是平行的状态,模板html中只可以拿到当前控制器下声明的变量。

 

三、对象对比:

        controller:

            function CCtrl($scope) {

                var vm = this;

                

                $scope.logThisAndScope = function() {

                    console.log(vm === $scope)

                }

            }

        vm与$scope实际上是不相等的,在console中我们可以看到

        vm: Constructor;

        $scope: $get.Scope.$new.Child;

        而在$scope中又包含了一个变量vm: Constructor   

        所以,$scope和this的实际关系,实际结构是

        $scope: {

            ...,

            vm: Constructor,

            ...

        }      

    那么我们可以整理如下:

    $scope 当控制器在写法上形成父子级关系时,子级没有的变量或方法父级会自动强加在子级身上,子级可以任意获取到当前父级的变量或方法,该种形式是不可逆的,即父级无法通过$scope获取到子级的任意变量或方法。

    this      则像一个独立的个体,所有东西都是由自己管理,也就不存在父子级变量混淆关系了。

   那数据共享该如何进行呢?数据业务逻辑我觉得还是交给更专业的service来处理吧。

    两种方式其实在性能上并无优劣之分,只有代码习惯的选择。

    这或许可以取决于我们观察的角度,其实可以理解为私用跟公用的区别!

 

Angular this vs $scope

标签:filter   函数   ddp   注入   状态   repeat   because   输出   default   

原文地址:http://www.cnblogs.com/oneplace/p/6209187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!