Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

javascript - Passing function with parameters in ng-class to get the class

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

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

1 Reply

0 votes
by (71.8m points)

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;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...