一尘不染

在angular +打字稿中使用templateRequest($ templateRequest不是函数)

angularjs

我正在建立一个指令,该指令应该将html文件放入dom并使用angular的compile进行编译

我收到一个错误:

$ templateRequest不是函数

显然我做错了,不知道是什么,

这是我的指令:

module Uni.Directives {

    export class uniTable implements ng.IDirective {

        public restrict: string = 'EA';

        public link: Function = (scope: ng.IScope,
            $templateRequest: ng.ITemplateRequestService,
            $compile: ng.ICompileService,
            element: ng.IAugmentedJQuery,
            attrs: ng.IAttributes) => {

           $templateRequest("template.html",false).then(function (html) {
                var template = angular.element(html);
                element.append(template);
                $compile(template)(scope);
            });
        }
    }

    angular
        .module('TModule')
        .directive('uniTable', [() => { return new Uni.Directives.uniTable() }]);


    // ******** End adding to module **********

}

阅读 222

收藏
2020-07-04

共1个答案

一尘不染

link-function
的第二个参数是element。如果您要注入$templateRequest,则$compile需要在构造函数中进行注入:

export class uniTable implements ng.IDirective {
    constructor(private $templateRequest: ng.ITemplateRequestService, private $compile: ng.ICompileService){

    }
    public restrict: string = 'EA';


    public link: Function = (scope: ng.IScope,
        element: ng.IAugmentedJQuery,
        attrs: ng.IAttributes) => {

       this.$templateRequest("template.html",false).then(function (html) {
            var template = angular.element(html);
            element.append(template);
            $compile(template)(scope);
        });
    }
}

angular
    .module('TModule')
    .directive('uniTable', ['$templateRequest','$compile',($templateRequest,$compile) => { return new Uni.Directives.uniTable($templateRequest,$compile) }]);

我建议在处理诸如指令功能之类的工厂功能时使用功能。下面这个结构:

function uniTable($templateRequest: ng.ITemplateRequestService, $compile: ng.ICompileService): ng.IDirective{
   return {
      restrict: 'EA',
      link: function(){
        $templateRequest()//doStuff
      }
   };
}
uniTable.$inject = ['$templateRequest', '$compile'];
angular.module('TModule')
.directive('uniTable', uniTable );
2020-07-04