【问题标题】:Set string as directive attribute value that maps to a member on the controller scope将字符串设置为映射到控制器范围内成员的指令属性值
【发布时间】:2016-12-11 15:08:27
【问题描述】:

所以这可能很难解释,但基本上我无法弄清楚如何将对象的字段值评估为指令将用于从范围分配数据的字符串......我有以下模板指令:

<hot-column ng-repeat="column in columns"
     data="{{column.fieldName}}" 
     title="column.title" 
     source="column.lookupField"> // <-- I need this to evaluate to the **"list_currency"** (which I will set on the scope) I cant figure out how this needs to look
</hot-column>

我的列对象是这样的:

[
    {   
        "fieldName": "ccy1",
        "title": "Ccy1",
        "lookupField": "list_currency"
    },
    {
        "fieldName": "ccy2",
        "title": "Ccy2"

    }
]

在控制器中我有这个范围变量:

$scope.list_currency = ["USD", "EUR"];

我尝试了一些组合,但都不起作用:

source="{{column.lookupField}}" // ==> angular.js:13424 Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{column.lookupField}}] starting at [{{column.lookupField}}].

source="'{{column.lookupField}}'"
source="column.lookupField"
source="'column.lookupField'"

【问题讨论】:

  • 试试{{[column.lookupField]}}
  • angular.js:13424 错误:[$parse:syntax] 语法错误:从 [{{[column.lookupField]}}] 开始的表达式 [{{[column.lookupField]}}] 的第 2 列中的标记“{”无效键{[column.lookupField]}}]。

标签: angularjs angularjs-directive handsontable


【解决方案1】:

我认为你的问题是你需要 angular 来评估表达式两次:

您需要首先评估“column.lookupField”表达式以返回“list_currency”,然后您需要评估“list_currency”表达式以返回实际数组。

您应该可以通过向控制器添加getColumnSource() 方法来做到这一点 - 如下所示:

$scope.getColumnSource = function(column) {
    return $scope.$eval(column.lookupField);
}

你的 html 然后看起来像这样:

<hot-column ng-repeat="column in columns"
     data="{{column.fieldName}}" 
     title="column.title" 
     source="getColumnSource(column)">
</hot-column>

【讨论】:

  • 不用 $eval 也可以做到这一点,只需 return $scope[column.lookupField]
  • 没错,尽管 $eval 给了你更多的灵活性,因为你可以在其中放置任何类型的角度表达式,而不仅仅是变量查找。或者,您可以更改原始列数据结构以包含对 list_currency 对象的直接引用 - 这样您就不需要查找或 $eval...
  • 感谢这项工作 - 想知道避免 eval 是否更高效?
  • @armensg90 从宏观上看,这可以忽略不计。 Angular 在每个摘要循环中对 html 页面上的每个角度表达式进行评估,每次发生变化时都会发生这种情况。显然,这一切最终都加起来了。如果你想避免它,你可以像 George 建议的那样进行查找。
  • 虽然这里更好的解决方案,imo,只是修改您的列数据结构以直接引用您的 list_currency 对象:"lookupField" : $scope.list_currency - 然后您可以在您的 html 中执行 source="column.lookupField"。更好的是,只需将 list_currency 设置为控制器中的局部变量,而不是将其放在范围内。一般来说,最好只将范围用于您的 html 需要查看的内容,而不是用不需要的内容来污染它。
猜你喜欢
  • 1970-01-01
  • 2021-12-01
  • 2021-11-29
  • 2018-01-22
  • 2020-12-27
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 2012-03-27
相关资源
最近更新 更多