armensg90 armensg90 - 4 months ago 17
AngularJS Question

Set string as directive attribute value that maps to a member on the controller scope

So this might be hard to explain but basically I cant figure out how to evaluate an object's field value to a string that the directive will use to assign data from the scope.... I have the following template directive:

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


where my column objects are like this:

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

}
]


And in the controller i have this scope variable:

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


I have tried some combinations none of which work:

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

Answer

I think your problem is that you need angular to evaluate the expression twice:

You need the "column.lookupField" expression to be evaluated first, to return "list_currency", but then you need the "list_currency" expression to be evaluated to return the actual array.

You should be able to do this by adding a getColumnSource() method to your controller - like this:

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

Your html then looks like this:

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