Reputation: 177
I've created a directive for managing (creating/updating/deleting) comments on customers in my application. Now I'd like the exact same comment functionality (look and feel) on users, so the only thing I need to do is replace my CustomersService with my UsersService. Both services have the same methods for "crud-ing" comments (I would make both implement an ICommentsService interface if possible in javascript).
My question is how can I in the best possible way reuse my already created View and Controller so I don't have to duplicate code?
My initial approach is to create two separate directives (CustomerComments and UserComments) that reference the same view and controller, but injecting a CustomersService or a UsersService respectively. The problem I'm facing with this, is how to keep the "DI-definition" in the directive declaration whilst having the controller in a separate file...?
This is my directive declaration:
angular.module('myApp').directive('myComments', [
function() {
'use strict';
return {
restrict: 'E',
scope: {
commentId: '='
},
templateUrl:'mycomments.html',
controller: 'CommentsCtrl', //<-- How to define injected objects here?
};
}
]);
...and this is my controller:
angular.module('myApp').controller('CommentsCtrl', [
'$scope',
'$q',
'CustomersService', //<-- These "DI-objects" should be defined in the directive declaration
function ($scope, $q, commentsService) {
$scope.addComment = function(comment){
commentsService.addComment(comment);
};
$scope.getComment = function(commentId){
retur commentsService.getComment(commentId);
};
//...etc...
}
]);
Or are there better ways to solve this?
Upvotes: 1
Views: 158
Reputation: 26838
Usually you do not explicitly register a directive's controller. That is somewhere you would have:
function CommentsCtrl($scope, $q, commentsService) {
And in your directive(s):
controller: ['$scope','$q','CustomersService', CommentsCtrl]
Upvotes: 1