unvrsltravlr unvrsltravlr - 2 months ago 29
Javascript Question

How to Dynamically Set Zingchart Attribute within Angular ng-Repeat

Using AngularJS, I'm trying to build a page which features a different dynamically generated Zingchart for each object in an array. My problem is that -- as the data and variable names are dynamically generated in my controller on page load -- I'm not sure how to properly reference them within the Zingchart directives.

In my controller, here is how the variables are dynamically generated:

function getWeeklyNflLines(){
oddsService.getWeeklyNflLines($stateParams.weekNumb).then(function(games){
vm.nflLines = games;
for (i=0; i<vm.nflLines.length; i++){
$scope[vm.nflLines[i].AwayAbbrev] = { [Zingchart json configuration goes here] }
}
}
}


Then, in my view where I try and produce the Zingchart, I've got:

<div ng-repeat="game in vm.nflLines>
<div zingchart zc-json="{{game.AwayAbbrev}}" zc-width="100%" zc-height="350px"></div>
</div>


So to review: I set the 'AwayAbbrev' $scope variable in the controller -- which should correspond to 'game.AwayAbbrev' within my ng-repeat -- but when I try to do this, I get the following error in my browser:

angular.js:13550 Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{game.AwayAbbrev}}] starting at [{game.AwayAbbrev}}].


I tried changing the zc-json attribute to ng-attr-zc-json to try and interpolate it, but that didn't work.

Any idea how I might accomplish this? Thanks in advance for any help!

====

EDIT: I should have mentioned that I also tried removing the curly braces altogether (e.g, zc-json="game.AwayAbbrev"), and though this took care of the error it returned no data.

===

EDIT #2: Please see Tjaart's answer below as this solved my problem. I will note there was one additional error in my code unrelated to my original question; I needed to include an id as a Zingchart attribute, which I incremented within my ng-repeat by index. So the final piece of code looked like this:

<div zingchart id="pick-chart[{{$index}}]" zc-json="nflLines[game.AwayAbbrev]" zc-width="100%" zc-height="350px"></div>

Answer

Instead of creating the json objects directly on $scope you can try do add them on a separate property:

$scope.nfLines = {};

function getWeeklyNflLines(){
  oddsService.getWeeklyNflLines($stateParams.weekNumb).then(function(games){
    vm.nflLines = games;
    for (i=0; i<vm.nflLines.length; i++){
      $scope.nfLines[vm.nflLines[i].AwayAbbrev] = { [Zingchart json configuration goes here] }
    }
  }
}

Then you can update your HTML to the following:

<div ng-repeat="game in vm.nflLines>
  <div zingchart zc-json="nfLines[game.AwayAbbrev]" zc-width="100%" zc-height="350px"></div>
</div>
Comments