本文介绍了只在被点击的元素上应用 ng-class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想在被点击的 button/element
上应用 ng-class
,我该怎么做?
JS 文件:
var classApp = angular.module('classApp', []);classApp.controller('classCtrl', function ($scope) {$scope.isActive = false;$scope.activeButton = function() {$scope.isActive = !$scope.isActive;}});
HTML 文件:
<button class="button" ng-class="{'active': isActive}" ng-click="activeButton()" type="button">点击我切换类</button><button class="button" ng-class="{'active': isActive}" ng-click="activeButton()" type="button">点击我切换类</button>
http://codepen.io/anon/pen/BjNyNe
解决方案
这是一个可能的解决方案:
控制器:
classApp.controller('classCtrl', function ($scope) {$scope.isActive = [假,假];$scope.activeButton = 函数(索引){$scope.isActive[index] = !$scope.isActive[index];}});
还有 html:
<button class="button" ng-class="{'active': isActive[0]}" ng-click="activeButton(0)" type="button">点击我切换类</button><button class="button" ng-class="{'active': isActive[1]}" ng-click="activeButton(1)" type="button">点击我切换类</button>
我的解决方案有效,但 @Shashank Agrawal 解决方案更好更干净.
I want to apply the ng-class
only on the button/element
that was clicked on, how would I do that?
JS file:
var classApp = angular.module('classApp', []);
classApp.controller('classCtrl', function ($scope) {
$scope.isActive = false;
$scope.activeButton = function() {
$scope.isActive = !$scope.isActive;
}
});
HTML file:
<div ng-app="classApp" ng-controller="classCtrl">
<button class="button" ng-class="{'active': isActive}" ng-click="activeButton()" type="button">Click Me to Toggle Class</button>
<button class="button" ng-class="{'active': isActive}" ng-click="activeButton()" type="button">Click Me to Toggle Class</button>
</div>
http://codepen.io/anon/pen/BjNyNe
解决方案
Here is a possible solution:
The controller:
classApp.controller('classCtrl', function ($scope) {
$scope.isActive = [false, false];
$scope.activeButton = function (index) {
$scope.isActive[index] = !$scope.isActive[index];
}
});
And the html:
<div ng-app="classApp" ng-controller="classCtrl">
<button class="button" ng-class="{'active': isActive[0]}" ng-click="activeButton(0)" type="button">Click Me to Toggle Class</button>
<button class="button" ng-class="{'active': isActive[1]}" ng-click="activeButton(1)" type="button">Click Me to Toggle Class</button>
</div>
EDIT: My solution works but @Shashank Agrawal solution is better and cleaner.
这篇关于只在被点击的元素上应用 ng-class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!