在NG-类参数传递函数来获取类 [英] Passing function with parameters in ng-class to get the class

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

问题描述

我试图用纳克级的角。我有返回基于我们发送它的参数类的功能。我怎样才能实现呢?

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 ?

下面是我的尝试:

<div ng-class="{ getClass(key) }" >

和在控制器:

getClass = function(keyVal){
    angular.forEach(myArray, function(value, id){
        if(value.key === keyVal){
            console.log(value.class);
            return value.class;
        }
    });
}

就返回一个字符串的作品。但我添加此anfular.forEach的那一刻,它停止。在调试器,循环工作正常,并返回正确的数据。

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.

我知道它可以通过一个过滤器acheved,但我想这样做只能这样。

I know it can be acheved by a filter, but I want to do this way only.

推荐答案

您768,16不能使用单大括号,只需删除它们,它会工作:

You shoud not use single curly-brackets, simply remove them and it will work:

<div ng-class="getClass(key)">

不过,对于您的使用情况下,它是更简单的前pression直接写入HTML(而不是调用一个函数)

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'">

请记住,NG-类ex pression可以返回

Keep in mind that the ng-class expression can return


  1. 的字符串:class1的类class2 3类

  2. 数组: [1级,类别2,3类]

  3. 地图:{1级:真正的,等级2:真实的,3类:真正}

  1. a string: "class1 class2 class3"
  2. an array: ["class1", "class2", "class3"]
  3. a map: "{class1: true, class2: true, class3: true}"

您新的问题是不同的。当您返回位于 angular.forEach 的东西,它只是退出循环,但它不是由该函数返回的getClass。因此,一个参考保持它:

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-类参数传递函数来获取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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