Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
859 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

  1. a string: "class1 class2 class3"
  2. an array: ["class1", "class2", "class3"]
  3. 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;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...