In my code I am passing an Array of JSON objects from my service to my controller and then to my directive to then be visualised.
Code in Controller:
(function(){
'use strict';
angular.module('dashboardApp').controller('DownloadCtrl', DownloadCtrl);
DownloadCtrl.$inject= ['DownloadService','$scope'];
function DownloadCtrl(DownloadService, $scope){
var self=this;
DownloadService.getRoutes()
.then(function(responseData){
self.routes = responseData.data;
});
}
})();
HTML code:
<div class="container" ng-controller="DownloadCtrl">
<donut-chart data='download.routes'></donut-chart>
</div>
Directive Code:
angular.module('dashboardApp').directive('donutChart',function(){
function link(scope,element,attr){
var dataSet = scope.data;
if(dataSet!==undefined){
var chart = c3.generate({
data: dataSet,
type:'donut'
});
}
};
return {
restrict: 'EA',
link : link,
scope: {
data: '='
}
};
});
If I scope.$watch $scope.data I notice that it appears once and there is no data assigned and then it appears again with data assigned to it. If I don't have the dataSet!==undefiend then the code will fail.
It works with the current setup but I feel that there is a better way than simply checking if dataSet!==undefined. I think I might of done things in the incorrect order or in the incorrect way.
I would want a way that would allow me to remove the dataSet!==undefiend
if(typeof scope.data === 'undefined'){return;}it returns without anything and thusly exists the function early. This prevents unnessary indentation from all your main code that should run. Not sure if that's the solution you want though. The only other way I can think of to always rutnr a scope.data value from your datasource.