如何使用 AngularJS 添加和删除类? [英] How to add and remove class with AngularJS?
本文介绍了如何使用 AngularJS 添加和删除类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个按钮可以像切换台一样工作.如果您单击一个按钮,它会变为活动状态并关闭"其他按钮.我使用 jQuery 做到了这一点,但想使用 AngularJS.这是我的代码:
HTML
JavaScript
.controller('AppCtrl', function($scope, $stateParams) {$('#weak').click(function() {$('#weak').addClass('active');$('#normal').removeClass('active');$('#strong').removeClass('active');});$('#normal').click(function() {$('#normal').addClass('active');$('#weak').removeClass('active');$('#strong').removeClass('active');});$('#strong').click(function() {$('#strong').addClass('active');$('#normal').removeClass('active');$('#weak').removeClass('active');});});
解决方案
你可以有 ng-click
可以切换 selected
标志,可以与 ng-class
绑定/解绑类.
标记
更好的方法
您可以使用 ng-repeat
轻松完成此操作,这将减少您的代码行.
标记
$scope.strengths = ["弱","正常","强"];
代码
I have a few buttons that work like switchers. If you click one it becomes active and "shuts down" other buttons. I did this using jQuery but would like to use AngularJS. Here is my code:
HTML
<div class="button-bar">
<a class="button button-energized" id="weak">weak</a>
<a class="button button-energized" id="normal">normal</a>
<a class="button button-energized" id="strong">strong</a>
</div>
JavaScript
.controller('AppCtrl', function($scope, $stateParams) {
$('#weak').click(function() {
$('#weak').addClass('active');
$('#normal').removeClass('active');
$('#strong').removeClass('active');
});
$('#normal').click(function() {
$('#normal').addClass('active');
$('#weak').removeClass('active');
$('#strong').removeClass('active');
});
$('#strong').click(function() {
$('#strong').addClass('active');
$('#normal').removeClass('active');
$('#weak').removeClass('active');
});
});
解决方案
You could have ng-click
that can toggle selected
flag, that could be use with ng-class
to bind / unbind class.
Markup
<div class="button-bar">
<a class="button button-energized" id="weak"
ng-class="{active: $parent.selected=='weak'}" ng-click="$parent.selected='weak'">
weak
</a>
<a class="button button-energized" id="normal"
ng-class="{active: selected=='normal'}" ng-click="selected='normal'">
normal
</a>
<a class="button button-energized" id="strong"
ng-class="{active: selected=='strong'}" ng-click="selected='strong'">
strong
</a>
</div>
Better way
You could easily do this by using ng-repeat
which will reduce your line of code.
Markup
$scope.strengths = ["weak","normal","strong"];
Code
<div class="button-bar">
<a class="button button-energized" id="{{strength}}"
ng-class="{active: $parent.selected == strength}"
ng-click="$parent.selected=strength"
ng-repeat="strength in strengths">
{{strength}}
</a>
</div>
这篇关于如何使用 AngularJS 添加和删除类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文