有多個angularJS指令相同的功能(使用chart.js之的角版本之一)多angularJS指令有我如何
現在我有一對夫婦的功能,我需要在這些指令使用。
什麼是讓我不再重複自己的好方法,所以從指令中刪除代碼並將它放在一個地方。由於該代碼無論如何都是相同的。 我已經研究了範圍的繼承,但還沒有能夠解決這個問題。
這是在多個指令使用的代碼:
$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);
}
一些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>
由於任何人,可以幫助!
也許我不說得對,但唯一的出版物是案例結構中的東西? – semptic
你應該使用對象:其中一個有像'byPeriod'等鍵作爲值的函數。當你需要'int'查找函數時,你應該這樣做'var key = Object.keys(object)[int]; object(key);' –
@semptic我列出的函數在多個指令中使用,所以我怎麼把它放到一箇中心位置。 – Maxicus