Currently, I am using the AngularJS factory method to retrieve data and passing that value to controllers.
In order to avoid creating separate functions, I would like to create a common function that can be utilized in all controllers.
How can I efficiently reuse code in a common function?
The different scopes such as scope.firstCard with 15 records, scope.secondCard with 6 records, scope.thirdCard with 130 records, and scope.fourthCard with 5 records each have varying values.
Please review the below factory code:
app.factory('commonService', ['$timeout', '$rootScope', '$state', '$window',
function($timeout, $rootScope, $state, $window) {
var renderData1 = function(scope) {
var convertedTime = scope.firstCard.forEach(function(card) {
if (card.Category == 'A') {
console.log("A");
} else if (card.Category == 'B') {
console.log("B");
} else if (card.Category == 'C') {
console.log("C");
} else if (card.Category == 'D') {
console.log("D");
} else if (card.Category == 'E') {
console.log("E");
}
});
return convertedTime;
};
var renderData2 = function(scope) {
var convertedTime = scope.secondCard.forEach(function(card) {
if (card.Category == 'A') {
console.log("A");
} else if (card.Category == 'B') {
console.log("B");
} else if (card.Category == 'C') {
console.log("C");
} else if (card.Category == 'D') {
console.log("D");
} else if (card.Category == 'E') {
console.log("E");
}
});
return convertedTime;
}
var renderData3 = function(scope) {
var convertedTime = scope.thirdCard.forEach(function(card) {
if (card.Category == 'A') {
console.log("A");
} else if (card.Category == 'B') {
console.log("B");
} else if (card.Category == 'C') {
console.log("C");
} else if (card.Category == 'D') {
console.log("D");
} else if (card.Category == 'E') {
console.log("E");
}
});
return convertedTime;
}
var renderData4 = function(scope) {
var convertedTime = scope.fourthCard.forEach(function(card) {
if (card.Category == 'A') {
console.log("A");
} else if (card.Category == 'B') {
console.log("B");
} else if (card.Category == 'C') {
console.log("C");
} else if (card.Category == 'D') {
console.log("D");
} else if (card.Category == 'E') {
console.log("E");
}
});
return convertedTime;
}
return {
renderData1: renderData1,
renderData2: renderData2,
renderData3: renderData3,
renderData4: renderData4
};
}]);
Instead of this approach, I aim to create a single function and use it across multiple controllers. How can I achieve this?
if (card.Category == 'A') {
console.log("A");
} else if (card.Category == 'B') {
console.log("B");
} else if (card.Category == 'C') {
console.log("C");
} else if (card.Category == 'D') {
console.log("D");
} else if (card.Category == 'E') {
console.log("E");
}
Given that this condition is prevalent in most controllers, is there a way to consolidate and reuse it in one central location?