I am trying to use ng-class of angular. I have a function which returns the class based on the parameters we send it. How can i achieve it ?
Here's what i tried:
<div ng-class="{ getClass(key) }" >
and in the controller:
getClass = function(keyVal){
angular.forEach(myArray, function(value, id){
if(value.key === keyVal){
console.log(value.class);
return value.class;
}
});
}
Just returning a string works. but the moment I add this anfular.forEach, it stops. In debugger, the loop is working fine and returning the right data.
I know it can be acheved by a filter, but I want to do this way only.
yes , you can do it.
To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.
So far we've looked at adding just single classes, which is something the NgClass directive can also help us with as it supports multiple classes. Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class.
AngularJS ng-class DirectiveIf it is a string, it should contain one or more, space-separated class names. As an object, it should contain key-value pairs, where the key is the class name of the class you want to add, and the value is a boolean value. The class will only be added if the value is set to true.
You shoud not use single curly-brackets, simply remove them and it will work:
<div ng-class="getClass(key)">
However for your use case it is even simpler to write the expression directly into the HTML (instead of calling a function)
<div ng-class="key + '-class'">
Keep in mind that the ng-class expression can return
"class1 class2 class3"
["class1", "class2", "class3"]
"{class1: true, class2: true, class3: true}"
Your new problem is different. When you return something inside angular.forEach
, it just exit the loop but it is not returned by the function getClass. So keep a reference to it:
getClass = function(keyVal) {
var theClass;
angular.forEach(myArray, function(value, id) {
if(value.key === keyVal) {
theClass = value.class;
}
});
return theClass;
}
Or you can have a simpler version:
getClass = function(keyVal) {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].key === keyVal) {
return myArray[i].class;
}
}
}
Update
You can achieve this by like this
myapp.controller('myCtrl', function ($scope) {
$scope.getClass = function(a){
return a;
}
});
and in template
<div ng-class="getClass('red')">text</div>
See My full working updated fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With