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
?