[英]What does passing `this` to a function inside ng-click expose?
Assume we have a button with a ng-click directive.It calls a function passing this
as an argument. 假设我们有一个带有ng-click指令的按钮。它调用一个函数将this
作为参数传递。 Upon inspection, the type of the parameter passed is found to be an object.But neither does it have any of the element properties , nor is it a jQuery selector. 经过检查,发现传递的参数类型是一个对象。但它既没有任何元素属性,也不是jQuery选择器。
What exactly gets passed ? 到底是什么?
ngClick
and similar directives are executed in context of the current scope. ngClick
和类似指令在当前范围的上下文中执行。 So this
refers scope object. 所以this
指的是范围对象。
If you don't have ngRepeat
, ngInclude
or other directive that creates new scope then you can check in controller function and verify that this ng-click="test(this)"
will pass something
as $scope
: 如果你没有创建新范围的ngRepeat
, ngInclude
或其他指令,那么你可以签入控制器函数并验证这个ng-click="test(this)"
会传递something
作为$scope
:
$scope.test = function(something) {
console.log(something === $scope); // => true
}
Another example. 另一个例子。 With ngRepeat you get new child scope per iteration, so in this case if you have this list: 使用ngRepeat,每次迭代都会获得新的子范围,因此在这种情况下,如果您有此列表:
<li ng-repeat="n in numbers">
<button ng-click="test(this)">{{n}}</button>
</li>
you will have something
being a child of the main $scope
: 你会有something
是主要$scope
的孩子:
$scope.test = function(something) {
console.log(something.$parent === $scope); // => true
};
Demo: http://plnkr.co/edit/nxxCn7SYUA4PfJpJoueu?p=info 演示: http : //plnkr.co/edit/nxxCn7SYUA4PfJpJoueu?p = info
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.