AngularJs 1:如何从指令声明中向控制器注入服务



我在应用程序中创建了一个用于管理(创建/更新/删除)客户评论的指令。现在我想在用户上完全相同的评论功能(外观和感觉),所以我唯一需要做的就是用UsersService替换我的CustomersService。这两个服务都有相同的"生成"注释的方法(如果可能的话,我会让它们都实现一个ICommentsService接口)。

我的问题是我如何能以最好的方式重用我已经创建的视图和控制器,所以我不必重复代码?

我最初的方法是创建两个单独的指令(CustomerCommentsUserComments),它们引用相同的视图和控制器,但分别注入CustomersServiceUsersService。我面临的问题是如何在指令声明中保持"di定义",同时在单独的文件中拥有控制器…?

这是我的指令声明:

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]

最新更新