I have 8 controllers using 12 common functions, but each controller has 3-4 unique functions. How can I avoid repeating myself in each controller while still utilizing a common service? Here is an example of my current code:
app.controller("ArticleController",['$scope','$http','dataService',function($scope,$http,dataService){
$scope.comments={};
$scope.articles = {articles:[]};
$scope.reachedEnd = false;
$scope.getArticles //implemented differently for each controller
//Here it is used to fetch latest articles
/* common 12 functions
to deal with dom events like new comments, upvotes, etc.
*/
function getArticlesSuccess(articles){
articles.articles.forEach(function(article){
$scope.articles.articles.push(article);
});
$scope.reachedEnd = articles.reachedEnd;
}
// Common functions handled by dataService
$scope.addToReadingList = function(id,userid){
dataService.addToReadingList(id,userid);
};
$scope.removeFromReadingList = function(id,userid){
dataService.removeFromReadingList(id,userid);
};
$scope.upvote = function(id,userid){
upvoteIncrementer(id,userid);
dataService.upvote(id);
};
$scope.deleteComment = function(commentId){
dataService.deleteComment(commentId);
};
var upvoteIncrementer = function(id,userid){
console.log(id);
$scope.articles.articles.forEach(function(article){
console.log(article);
if(article && article._id === id && !article.votes.set){
if(article.votes.down.indexOf(userid)>-1){
article.votes.down.splice(article.votes.down.indexOf(userid));
console.log('removed vote');
}
article.votes.up.push(userid);
article.votes.set = true;
}
});
}
// Similar pattern for other operations
}]);
Code snippet for another controller:
app.controller("AnotherController",['$scope','$http','dataService',function($scope,$http,dataService){
$scope.comments={};
$scope.articles = {articles:[]};
$scope.reachedEnd = false;
$scope.getArticles //implemented differently for each of the controllers
//Here it is used to fetch top articles by the day
/* common 12 functions */
}]);
EDIT: Added dataservice.js
(function(){
angular.module('newstalk')
.factory('dataService',['$http','$q',dataService]);
function dataService($http,$q){
return {
getArticles : getArticles,
postComments : postComments,
addToReadingList : addToReadingList,
getReadingList : getReadingList,
upvote : upvote,
downvote : downvote,
getComments : getComments,
removeFromReadingList : removeFromReadingList,
deleteComment : deleteComment
};
// Functions logic here
}
})()
Please suggest a way to reduce code duplication and make changes in only one place to affect all controllers.