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:
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
You are returning value from callback function of for each method..which not correct..because u r expected return value from getclass method Try this
$scope.getclass =function(k){
Var c="";
angular.foreach(arr,function(v){
//to do
c=k;
});
return c;
};
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;
}
}
}