[英]Add class to a div dynamically in angular js
I have a div like this 我有这样的div
<div ng-model="star"></div>
I want to add a class 'active' to this div in angular js. 我想在angular js中向该div添加一个“活动”类。 I tried like this in my angular js controller
我在我的角度js控制器中尝试过这样
$scope.star.addClass('active');
But,I am getting error. 但是,我得到了错误。 I am new to angular js.
我是angular js的新手。 please help me...
请帮我...
Try this: 尝试这个:
<div ng-class="{ active: star == 'yes', 'in-active': star == 'no' }" ng-bind="star"></div>
You can have one or more classes assigned based on the expression (true or false). 您可以基于表达式分配一个或多个类(对或错)。 If a class name has a hyphen, enclose in single quote.
如果类名带有连字符,请用单引号引起来。 This is a better approach and preferred than changing in controller.
与更改控制器相比,这是一种更好的方法,更可取。 Also, because this is a div, you have to do ng-bind, not ng-model.
另外,由于这是一个div,因此您必须执行ng-bind,而不是ng-model。 ng-model works on fields like input.
ng-model适用于输入之类的字段。
UPDATE: 更新:
Since you insist on changing the class in code, here it is: 由于您坚持要更改代码中的类,因此它是:
$("div[ng-bind='star']").addClass('active');
If you want to access change class dynamically then you can put watch on your star variable in your controller like below : 如果要动态访问更改类,则可以将监视放在控制器中的star变量上,如下所示:
$.watch('star',function(newVal, oldVal){
// put your code to here based on new value and old value
// you can add class to your div like :
// angular.element("div[ng-bind='star']").addClass('active');
});
Using a variable to control your class 使用变量控制班级
<div ng-class="customClass"></div>
in controller 在控制器中
$scope.customClass = 'active custom-class1';
so, you can use if-else to change class name 因此,您可以使用if-else更改类名
if (something) {
$scope.customClass = 'active custom-class1';
} else {
$scope.customClass = 'deactive custom-class2';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.