jQuery 在 angularjs 中获取 $this
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16163978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the $this in angularjs
提问by Bhumi Singhal
Here is my issue.
这是我的问题。
HTML structure :
HTML 结构:
<tr><td><a ng-click=aClick()>Click Me</a></td></tr>
I cannot have any id/class associated with the and
我不能有任何与 和 相关联的 id/class
What I require is that on the click of 'Click Me', the <tr>
gets hidden. I need a jQuery solution. Some how I am not able to use $(this)
.
我需要的是点击“点击我”,<tr>
隐藏。我需要一个 jQuery 解决方案。有些我无法使用$(this)
.
FUNCTION:
功能:
$scope.aClick = function() {
$(this).parent().parent().css('display','block');
};
But this statement gives me an error.
但是这个声明给了我一个错误。
回答by Arun P Johny
Note: I wouldn't recommend using dom manipulation in a controller, you can write a directive to do this. That said you can use the $event
to get the event object, from which you can get the event target and use it with jquery.
注意:我不建议在控制器中使用 dom 操作,您可以编写一个指令来执行此操作。也就是说,您可以使用$event
来获取事件对象,您可以从中获取事件目标并将其与 jquery 一起使用。
<tr><td><a ng-click="aClick($event)">Click Me</a></td></tr>
And
和
$scope.aClick = function(event) {
$(event.target).parent().parent().css('display','none');
};
Demo: Plunker
演示:Plunker
Update
A more appropriate angular solution will be is to use ng-hide
更新
更合适的角度解决方案是使用 ng-hide
<tr ng-hide="hideRow"><td><a ng-click="hideRow = true">Click Me</a></td></tr>
Demo: Plunker
演示:Plunker
Updated demowith ng-repeat
使用 ng-repeat更新演示
回答by NilsH
Since you're using angular, you should very seldom need to do actual dom manipulation. Instead, check out the ng-hide/ng-showdirective that should do this for you.
由于您使用的是 angular,因此您应该很少需要进行实际的 dom 操作。相反,请查看应该为您执行此操作的ng-hide/ng-show指令。
An example from the Angular docs:
Angular 文档中的一个示例:
<body>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</body>
Edit
编辑
If the variable in the expression is updated asynchronously, you can force an updated with $scope.$apply
如果表达式中的变量是异步更新的,您可以使用 $scope.$apply
回答by Minko Gechev
回答by lokers
why don't you do something simple like this? I assume you run this in loop...
你为什么不做一些像这样简单的事情?我假设你在循环中运行它......
<div ng-repeat="row in table">
<tr>
<td>
<a ng-class="{'hideme': hiddenRows[row.id]}" ng-click="hiddenRows[row.id] = true">Click Me</a>
</td>
</tr>
</div>
or even better
甚至更好
<div ng-repeat="row in table">
<tr ng-show="!hiddenRows[row.id]">
<td>
<a ng-click="hiddenRows[row.id] = true">Click Me</a>
</td>
</tr>
</div>
(I didn't test it but it should give you idea)
(我没有测试它,但它应该给你想法)