3

I want to integrate d3.js and angularjs. I have to draw a ling graph. Data is loaded from tsv file. I am having problem in rending the graph and error is that data has not yet been loaded and graph is rendered. I want to that when data is loaded in scope variable, graph should be rendered else not. Please help. Here is code of controller

phonecatControllers.controller('MainCtrl', ['$scope',
     function($scope) {
       d3.tsv("sample.tsv", function(error, data) {
       $scope.d3Data = data;
 });
}]);

And here is directive code

directives.directive('d3Bar', [ function() {
return {
    restrict : 'E',
    scope : {
        data : '='
    },
    link : function(scope, element) {
        scope.$watch('data', function(newData, oldData) {
            drawLine(newData);
        }, true);
    }
}

}

and html is

<body ng-controller='MainCtrl'>
    <d3-bar data='d3Data'></d3-bar>

</body>
hard coder
  • 5,449
  • 6
  • 36
  • 61

2 Answers2

9

Use ng-if with your condition that data is available or not, to resolve this problem.

HTML:

<body ng-controller='MainCtrl'>
  <div ng-if="d3Data">
    <d3-bar data='d3Data'></d3-bar>
  <div>
</body>

So your directive will load only when d3Data has any data.

Rubi saini
  • 2,515
  • 23
  • 21
  • This will fail if you have an empty object link on data see http://stackoverflow.com/questions/32586180/how-to-check-for-an-empty-object-in-an-angularjs-view – Jimmy Kane Apr 30 '17 at 15:30
6

put an if control in your watch to check if your data item is ready to go or not

directives.directive('d3Bar', [function() {
    return {
        restrict : 'E',
        scope : {
            data : '='
        },
        link : function(scope, element) {
            scope.$watch('data', function(newData, oldData) {
                if(newData){
                    drawLine(newData);
                }
            }, true);
        }
    }
}])
fejese
  • 4,601
  • 4
  • 29
  • 36
Poyraz Yilmaz
  • 5,847
  • 1
  • 26
  • 28
  • now line $scope.d3Data = data; of controller does not trigger any event to watcher function. Inititally watcher function runs with oldData and newData both as undefined. – hard coder Jul 04 '14 at 10:21
  • @sarvesh then your d3Data object is never changed... Please check that your d3Data has right value... – Poyraz Yilmaz Jul 04 '14 at 10:33
  • @wickY26- I have debuged the code properly control first goes to watch function with both old and new data as undefined and then goes to line `$scope.d3Data = data` of controller in which I can see data variable has an array of values after this line watch function doesn't get a run as expected – hard coder Jul 07 '14 at 06:30