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

后端 未结 3 1984
闹比i
闹比i 2020-12-11 00:45

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:

相关标签:
3条回答
  • 2020-12-11 00:56

    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

    0 讨论(0)
  • 2020-12-11 01:06

    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;
       };
    
    0 讨论(0)
  • 2020-12-11 01:12

    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;
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题