使用ng-click切换父元素的类? [英] Toggle class of parent element using ng-click?
问题描述
我有一些要转换为Angular的JavaScript:
I have some javascript that I'm trying to convert into Angular:
$('.col-lg .fa-clock-o').click(function(e){
$(this).parent().toggleClass('set-time');
e.preventDefault()
});
我尝试将以下内容添加到包含链接的子元素中,但是它不起作用,也许有一种适当的角度"方式可以做到这一点?
I've tried adding the following to the child element containing the link, but it doesn't work, maybe theres a proper 'angular' way to do this instead?
<a href="#" class="fa fa-clock-o" aria-hidden="true" ng-click="$(this).parent().toggleClass('set-time')"></a>
推荐答案
执行此操作的另一种角度"方法是设置一个变量,该变量表示父元素上是否存在set-time
类.默认情况下,这将是undefined
这是虚假的.
A more 'Angular' way to do this would be to set a variable which represents whether or not the set-time
class is present on the parent element. By default this would be undefined
which is falsy.
然后在ng-click中进行切换,您可以将值设置为与当前值相反的值.
Then to toggle it in your ng-click you can just set the value to be the opposite of what it currently is.
<div ng-class="{'set-time': setTimeClass}">
<a href class="fa fa-clock-o" aria-hidden="true" ng-click="setTimeClass = !setTimeClass">toggle class</a>
</div>
这是一个可行的示例:
var app = angular.module('app', []);
.set-time {
background :red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-class="{'set-time': setTimeClass}">
<a href class="fa fa-clock-o" aria-hidden="true" ng-click="setTimeClass = !setTimeClass">toggle class</a>
</div>
</div>
这篇关于使用ng-click切换父元素的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!