在 ng-class 中传递带参数的函数以获取类 [英] Passing function with parameters in ng-class to get the class

查看:21
本文介绍了在 ng-class 中传递带参数的函数以获取类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ng-class 的角度.我有一个函数,它根据我们发送的参数返回类.我怎样才能实现它?

这是我尝试过的:

在控制器中:

getClass = function(keyVal){angular.forEach(myArray, function(value, id){if(value.key === keyVal){控制台日志(值.类);返回值.class;}});}

只需返回一个字符串即可.但是当我添加这个 anfular.forEach 时,它停止了.在调试器中,循环工作正常并返回正确的数据.

我知道它可以通过过滤器实现,但我只想这样做.

解决方案

您不应该使用单个花括号,只需将它们删除即可:

但是对于您的用例,将表达式直接写入 HTML(而不是调用函数)会更简单

记住 ng-class 表达式可以返回

  1. 一个字符串:"class1 class2 class3"
  2. 一个数组:["class1", "class2", "class3"]
  3. 地图:"{class1: true, class2: true, class3: true}"

更新

您的新问题有所不同.当您在 angular.forEach 中返回某些内容时,它只会退出循环,但不会由函数 getClass 返回.因此,请保留对它的引用:

getClass = function(keyVal) {var theClass;angular.forEach(myArray, function(value, id) {if(value.key === keyVal) {theClass = value.class;}});返回类;}

或者你可以有一个更简单的版本:

getClass = function(keyVal) {for (var i = 0; i < myArray.length; i++) {if (myArray[i].key === keyVal) {返回 myArray[i].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.

解决方案

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

这篇关于在 ng-class 中传递带参数的函数以获取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆