使用 ng-click 在 angularJs 中添加和删除类 [英] adding and removing classes in angularJs using ng-click
本文介绍了使用 ng-click 在 angularJs 中添加和删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试如何使用 ngClick 添加一个类.我已将我的代码上传到 plunker 点击此处.查看 angular 文档,我无法弄清楚应该完成的确切方式.下面是我的代码片段.有人可以指导我朝着正确的方向前进
I am trying to work how to add a class with ngClick. I have uploaded up my code onto plunker Click here. Looking at the angular documentation i can't figure out the exact way it should be done. Below is a snippet of my code. Can someone guide me in the right direction
<div ng-show="isVisible" ng-class="{'selected': $index==selectedIndex}" class="block"></div>
控制器
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
推荐答案
您只需要将一个变量绑定到指令ng-class"中并从控制器中更改它.以下是如何执行此操作的示例:
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red";
$scope.changeClass = function(){
if ($scope.class === "red")
$scope.class = "blue";
else
$scope.class = "red";
};
});
.red{
color:red;
}
.blue{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>
</body>
这是处理 jsFiddle
这篇关于使用 ng-click 在 angularJs 中添加和删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文