AngularJs 1:如何从指令声明中向控制器注入服务
AngularJs 1: How to inject a service to a controller from the directive declaration
我在我的应用程序中创建了一个管理(creating/updating/deleting)客户评论的指令。
现在我想要对用户使用完全相同的评论功能(外观和感觉),所以我唯一需要做的就是用我的 UsersService[= 替换我的 CustomersService 32=]。
两种服务都具有相同的 "crud-ing" 评论方法(如果可能的话,我会让两者实现 ICommentsService 接口 javascript)。
我的问题是如何以最好的方式重用我已经创建的视图和控制器,这样我就不必重复代码?
我最初的方法是创建两个单独的指令(CustomerComments 和 UserComments),它们引用相同的视图和控制器,但注入一个CustomersService 或 UsersService 分别。我面临的问题是如何将 "DI-definition" 保留在指令声明中,同时将控制器放在单独的文件中...?
这是我的指令声明:
angular.module('myApp').directive('myComments', [
function() {
'use strict';
return {
restrict: 'E',
scope: {
commentId: '='
},
templateUrl:'mycomments.html',
controller: 'CommentsCtrl', //<-- How to define injected objects here?
};
}
]);
...这是我的控制器:
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...
}
]);
或者有更好的方法来解决这个问题吗?
通常您不会显式注册指令的控制器。那是你会拥有的地方:
function CommentsCtrl($scope, $q, commentsService) {
在您的指令中:
controller: ['$scope','$q','CustomersService', CommentsCtrl]
我在我的应用程序中创建了一个管理(creating/updating/deleting)客户评论的指令。 现在我想要对用户使用完全相同的评论功能(外观和感觉),所以我唯一需要做的就是用我的 UsersService[= 替换我的 CustomersService 32=]。 两种服务都具有相同的 "crud-ing" 评论方法(如果可能的话,我会让两者实现 ICommentsService 接口 javascript)。
我的问题是如何以最好的方式重用我已经创建的视图和控制器,这样我就不必重复代码?
我最初的方法是创建两个单独的指令(CustomerComments 和 UserComments),它们引用相同的视图和控制器,但注入一个CustomersService 或 UsersService 分别。我面临的问题是如何将 "DI-definition" 保留在指令声明中,同时将控制器放在单独的文件中...?
这是我的指令声明:
angular.module('myApp').directive('myComments', [
function() {
'use strict';
return {
restrict: 'E',
scope: {
commentId: '='
},
templateUrl:'mycomments.html',
controller: 'CommentsCtrl', //<-- How to define injected objects here?
};
}
]);
...这是我的控制器:
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...
}
]);
或者有更好的方法来解决这个问题吗?
通常您不会显式注册指令的控制器。那是你会拥有的地方:
function CommentsCtrl($scope, $q, commentsService) {
在您的指令中:
controller: ['$scope','$q','CustomersService', CommentsCtrl]