当函数不在指令内时,如何将服务传递到AngularJS指令中?

当函数不在指令内时,如何将服务传递到AngularJS指令中?,angularjs,Angularjs,我有这个指示: app.directive('htmlTemplate', htmlTemplate); function htmlTemplate() { return { restrict: 'A', templateUrl: function (elem, attrs) { return "/Content/app/admin/templates/" + attrs.templateUrl; },

我有这个指示:

app.directive('htmlTemplate', htmlTemplate);

function htmlTemplate() {
    return {
        restrict: 'A',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}
我见过很多指令的例子,其中所有内容都包含在一个块中,但函数不是像这里这样分开的


有人能告诉我如何将stateService注入指令吗?

由于参数是动态注入的,您可以尝试以下方法:

app.service("YourService", function() {

});

app.directive('htmlTemplate',['YourService', htmlTemplate]);

function htmlTemplate(yourService) {
    return {
        restrict: 'A',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}

无缩小保护:

app.directive('htmlTemplate', htmlTemplate);

function htmlTemplate(stateService) {
    return {
        restrict: 'A',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}
app.directive('htmlTemplate', ['stateService', htmlTemplate]);

function htmlTemplate(stateService) {
    return {
        restrict: 'A',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}
具有小型化保护:

app.directive('htmlTemplate', htmlTemplate);

function htmlTemplate(stateService) {
    return {
        restrict: 'A',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}
app.directive('htmlTemplate', ['stateService', htmlTemplate]);

function htmlTemplate(stateService) {
    return {
        restrict: 'A',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}

很好很清楚,不像我见过的其他答案。