I have multiple angularJS directives (that use one of the angular versions of chart.js)
Now I have a couple of functions that I need to use in these directives.
What is a good way to make me not repeat myself, so remove the code from the directives and have it in one place. Since that code is identical anyways. I've looked into inheritance of scopes but haven't been able to solve this problem yet.
This is the code that is used in multiple directives:
$scope.widgetData = false;
$scope.graphData = false;
$scope.graphSelectorIndex = 0;
$scope.graphSelector = [
{ 'byPeriod' : 'Periode'},
{ 'byHour' : 'Uur' },
{ 'byDay' : 'Dag'}
];
$scope.graphSelectorByText = function (text) {
switch (text) {
case ('byPeriod'):
$scope.selector = 'byPeriod'
$scope.graphData = $scope.allGraphData.byPeriod;
$scope.graphType = 'Line';
break;
case ('byDay'):
$scope.selector = 'byDay'
$scope.graphData = $scope.allGraphData.byDay;
$scope.graphType = 'Line';
break;
case ('byHour'):
$scope.selector = 'byHour'
$scope.graphData = $scope.allGraphData.byHour;
$scope.graphType = 'Bar';
break;
}
}
$scope.graphSelectorByInt = function (int) {
switch (int) {
case (0):
$scope.selector = 'byPeriod';
$scope.graphData = $scope.allGraphData.byPeriod;
$scope.graphType = 'Line';
break;
case (1):
$scope.selector = 'byDay';
$scope.graphData = $scope.allGraphData.byDay;
$scope.graphType = 'Line';
break;
case (2):
$scope.selector = 'byHour';
$scope.graphData = $scope.allGraphData.byHour;
$scope.graphType = 'Bar'
break;
}
}
$scope.graphSelectorPrev = function () {
$scope.graphSelectorIndex--;
if ($scope.graphSelectorIndex < 0) {
$scope.graphSelectorIndex = $scope.graphSelector.length-1;
}
$scope.graphSelectorByInt($scope.graphSelectorIndex);
console.log($scope.graphSelectorIndex);
}
$scope.graphSelectorNext = function () {
$scope.graphSelectorIndex++;
if ($scope.graphSelectorIndex >= $scope.graphSelector.length) {
$scope.graphSelectorIndex = 0;
}
$scope.graphSelectorByInt($scope.graphSelectorIndex);
console.log($scope.graphSelectorIndex);
}
Some html:
<div class="controls">
<span class="btn_arrow previous inactive" ng-click="graphSelectorPrev()">Vorige</span>
<p>{+ selector +}</p>
<span class="btn_arrow next" ng-click="graphSelectorNext()">Volgende</span>
</div>
Thanks to anyone that can help!
intyou should do something like thatvar key = Object.keys(object)[int]; object(key);