'this' 是否总是指向模板中的当前范围?
Does 'this' always point on the current scope in a template?
在模板中使用 this
获取当前范围的引用总是安全的吗?
<span ng-click="log(this)">
Is my onclick parameter always the current controllers scope?
</span>
下面是fiddle来说明我的意思。
也四处搜索,但在文档中找不到任何关于此的观点。它似乎有效,但我不想依赖未记录的功能。如果可以,请link为此提供正确的文档。
this
指控制器指令的$scope。
例如:
<div ng-controller="myCntrl">
<span ng-click="log(this)">
Is my onclick parameter always the current controllers scope?
</span>
</div>
因此,this
指的是 myCntrl
的 $scope。
表达式 log(this)
是根据作用域求值的,scope
对象中也有一个 this
属性 指向它自己的引用。因此它将根据范围评估 this
将产生范围本身。例如,您还可以传递 $parent
并且您会看到它将指向父作用域,因为表达式中的参数根据当前作用域进行评估将产生 scope['$parent']
类似地它恰好作用于作用域['this'] 也是。 在 angular 上下文中使用 ng-click="method(this)"
与在 DOM 元素上执行 onclick="somefunc(this)"
完全不同。 Angular 能够扩展它只是因为它有一个 属性,名称 this
附加到作用域对象。
另一件事是你不需要传递 this
,否则该方法是 运行 通过对范围对象进行评估,因此引用 this 将产生范围本身。即你也可以做 ng-click="log()"
并且在日志方法中你可以引用 this
作为元素绑定到的当前范围。例如,如果您使用 controllerAs
语法并且您正在调用:
<div ng-controller="MyOtherCtrl as vm">
<span ng-click="vm.log(this)">Click on me, if background gets teal, then this points on the child controllers scope</span>
</div>
现在 this
将不再是控制器实例(这是您通常期望的),而只是 scope
对象本身,因为它将表达式计算为 scope.vm.log(scope.this)
在控制器的上下文中使用 $scope
总是更安全,除非您特别想引用由于某些指令(通过某些 ng-repeat,ng -if 等..) 包装那个特定的上下文。还请记住,属性在子作用域中以原型方式继承(独立作用域指令除外)。
据我所知,没有记录任何链接或任何内容,但源代码本身就是官方记录。 Angular 使用 $parse
扩展表达式,如果您看到 source code,您可以看到 angular 使用 function.apply
和上下文调用表达式。
在模板中使用 this
获取当前范围的引用总是安全的吗?
<span ng-click="log(this)">
Is my onclick parameter always the current controllers scope?
</span>
下面是fiddle来说明我的意思。
也四处搜索,但在文档中找不到任何关于此的观点。它似乎有效,但我不想依赖未记录的功能。如果可以,请link为此提供正确的文档。
this
指控制器指令的$scope。
例如:
<div ng-controller="myCntrl">
<span ng-click="log(this)">
Is my onclick parameter always the current controllers scope?
</span>
</div>
因此,this
指的是 myCntrl
的 $scope。
表达式 log(this)
是根据作用域求值的,scope
对象中也有一个 this
属性 指向它自己的引用。因此它将根据范围评估 this
将产生范围本身。例如,您还可以传递 $parent
并且您会看到它将指向父作用域,因为表达式中的参数根据当前作用域进行评估将产生 scope['$parent']
类似地它恰好作用于作用域['this'] 也是。 在 angular 上下文中使用 ng-click="method(this)"
与在 DOM 元素上执行 onclick="somefunc(this)"
完全不同。 Angular 能够扩展它只是因为它有一个 属性,名称 this
附加到作用域对象。
另一件事是你不需要传递 this
,否则该方法是 运行 通过对范围对象进行评估,因此引用 this 将产生范围本身。即你也可以做 ng-click="log()"
并且在日志方法中你可以引用 this
作为元素绑定到的当前范围。例如,如果您使用 controllerAs
语法并且您正在调用:
<div ng-controller="MyOtherCtrl as vm">
<span ng-click="vm.log(this)">Click on me, if background gets teal, then this points on the child controllers scope</span>
</div>
现在 this
将不再是控制器实例(这是您通常期望的),而只是 scope
对象本身,因为它将表达式计算为 scope.vm.log(scope.this)
在控制器的上下文中使用 $scope
总是更安全,除非您特别想引用由于某些指令(通过某些 ng-repeat,ng -if 等..) 包装那个特定的上下文。还请记住,属性在子作用域中以原型方式继承(独立作用域指令除外)。
据我所知,没有记录任何链接或任何内容,但源代码本身就是官方记录。 Angular 使用 $parse
扩展表达式,如果您看到 source code,您可以看到 angular 使用 function.apply
和上下文调用表达式。