angular ng-repeat with directive

2019-07-24 14:50发布

问题:

i'm new to angular and have the following issue where i need assistence. I'm using angular charts directives http://jtblin.github.io/angular-chart.js/ to build a chart board. I got the follwoing scenario:

I have a directive a view and anenter code here associated controller. Inside the controller there should be an array charts[] which holds objects. these objects should be two-way binded with the chart directive. What is the appropriate way to do so? I will bild my charts dynamically without any controller attached to each chart. Is that possible?

reportView.html

<div ng-repeat="c in charts">
<chart></chart>
<div>

reportViewController.js

angular.module('app').controller('reportViewController', reportViewCtrl);

reportViewCtrl.$inject = ['$scope', '$log', 'RefinerService', 'appConfig'];


function reportViewCtrl($scope, $log, RefinerService, appConfig) {
    $scope.charts = [];
    var chart = {
                ID: 1
                , Visible: true
                , Type: "chart-line"
                , Data: [
                    [65, 59, 80, 81, 56, 55, 40]
                    , [28, 48, 40, 19, 86, 27, 90]
                ]
                    , Labels: ['2006', '2007', '2008', '2009', '2010', '2011', '2012']
                    , Series: ['Product A', 'Product B']

    }
    $scope.charts.push(chart);
}

chartTemplate.html

<div class="chart-container" flex>
<canvas class="chart {{c.Type}}" 
  data="{{c.Data}}" 
  labels="{{c.Labels}}" 
  series="{{c.Series}}">
</canvas>
</div>

directive.js

angular.module('app').directive('chart', function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/chartTemplate.html',
        scope: {
            id: '@id',
            type: '@type'
        }
    };
});

help would be appreciated! cheers philipp

回答1:

Edit: Final fiddle showing working example, in collaboration with OP - https://plnkr.co/edit/8fJ4u0U2fL4lYTioCbG0?p=preview

You need to pass the "c" from the ng-repeat into the chart directive.

Here is a fiddle to demonstrate: http://jsfiddle.net/8zwmt18L/1/

<div ng-repeat="c in charts">
<chart chart-data="c"></chart>
<div>

In your directive:

angular.module('app').directive('chart', function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/chartTemplate.html',
        scope: {
            chartData: '='
        }
    };
});

In your directive template:

<div class="chart-container" flex>
<canvas class="chart chart-base" 
  chart-type="chartData.Type"
  data="chartData.Data" 
  labels="chartData.Labels" 
  series="chartData.Series">
</canvas>
</div>

In the data for the charts, your types will need to be "Line" or "Bar", and not "chart-line" or "chart-bar"