0

plunkr

I have a d3 chart that gets the data from other parts of the page. So I used a directive to encapsulate d3 related code and controller to supply the data to directive. I have setup binding to data using bindToController.

Previously I was using $scope.watch to react to future data that the graph needs to display and it worked well. Recently I upgraded the code to be on par with Angular 1.4, so that I can eventually move to components in Angular 1.5. This means I introduced controllerAs and bindToController into the mix.

The only problem I have now is that when there is an update to data, I cannot see the latest changes inside the link function. How can I fix this?

Directive

app.directive('barChart', function () {
    var chart = d3.custom.barChart();
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        bindToController: {
            data: '='
        },
        controller: 'mainCtrl',
        controllerAs: 'ctrl',
        link: function (scope, element, attrs, ctrl) {
            var chartEl = d3.select(element[0]);

            chartEl.datum(ctrl.data).call(chart);

            // when the code is pre ng 1.3, I used scope
            // scope.$watch('data', function (newVal, oldVal) {
            //     console.log('before', JSON.stringify(oldVal), 'after', JSON.stringify(newVal));
            //     chartEl.datum(newVal).call(chart);
            // });
        }
    }
});

Controller

app.controller('mainCtrl', function mainCtrl(appService) {
    this.data = [19, 12, 43, 24];

    this.update = function (d, i) {
        this.data = appService.GetCurrentData();
    };
});

Should I move the $scope.$watch into the controller? If so, what is the real benefit I get with removing the scope in the controller, if I still have to use $scope.$watch?

Animesh
  • 4,926
  • 14
  • 68
  • 110
  • You should wrap your `chartEl.datum(ctrl.data).call(chart);` inside `$timeout` like `$timeout(function(){ chartEl.datum(ctrl.data).call(chart); })`, for more explanation please look into [this answer] somewhat relative(http://stackoverflow.com/a/31013435/2435473). – Pankaj Parkar Sep 21 '16 at 18:51
  • @PankajParkar: I tried having a $timeout and it did not work, sorry. – Animesh Sep 22 '16 at 00:06
  • Coul you please add plunkr then – Pankaj Parkar Sep 22 '16 at 04:16
  • Here is the [plunkr](https://plnkr.co/edit/eAzaJuxbLl73dBLU41jQ?p=preview) – Animesh Sep 23 '16 at 19:20

0 Answers0