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
- a string:
"class1 class2 class3"
- an array:
["class1", "class2", "class3"]
- a map:
"{class1: true, class2: true, class3: true}"
Update
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;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…