Dygraphs not working with ng-repeat

前端 未结 1 1648
小蘑菇
小蘑菇 2020-12-17 06:19

I\'m new to AngularJS and building a dashboard with dygraphs.

Tried to put the example code from the dygraphs website in an ng-repeat-list, just to test. Expected t

相关标签:
1条回答
  • 2020-12-17 07:10

    Your problem is that Angular will repeat your <div id="graph"> n times. So you now have n times div with id of 'graph' which are siblings. Therefore, when you call document.getElementById('graph'), that won't work very well.

    That said, I don't know how well script tags inside ng-repeat works either, seems like a very strange use case.

    The proper way to do this (as with all DOM related operations), is to use a directive. Here's an example:

    Javascript:

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function($scope) {
        $scope.graphs = [
            {
                data: [ [1,10,100], [2,20,80], [3,50,60], [4,70,80] ],
                opts: { labels: [ "x", "A", "B" ] }
    
            },
            {
                data: [ [1,10,200], [2,20,42], [3,50,10], [4,70,30] ],
                opts: { labels: [ "label1", "C", "D" ] }
    
            }
        ];
    });
    
    myApp.directive('graph', function() {
        return {
            restrict: 'E', // Use as element
            scope: { // Isolate scope
                data: '=', // Two-way bind data to local scope
                opts: '=?' // '?' means optional
            },
            template: "<div></div>", // We need a div to attach graph to
            link: function(scope, elem, attrs) {
    
                var graph = new Dygraph(elem.children()[0], scope.data, scope.opts );
            }
        };
    });
    

    HTML:

    <div ng-controller="MyCtrl">
        <graph ng-repeat="graph in graphs" data="graph.data" opts="graph.opts"></graph>
    </div>
    

    JSFiddle

    Hope this helps!

    0 讨论(0)
提交回复
热议问题