在 angular + typescript 中使用 templateRequest($templateRequest 不是函数) [英] Using templateRequest in angular + typescript ($templateRequest not a function)
问题描述
我正在构建一个指令,该指令应该采用 html 文件,将其放入 dom 并使用 angular 的 compile 进行编译
I'm building a directive which supposed to take html file, place it in dom and compile it with angular's compile
我收到一个错误:
$templateRequest 不是函数
$templateRequest is not a function
显然我做错了什么,不知道是什么,
Clearly I am doing something wrong, don't know what,
这是我的指令:
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 **********
}
推荐答案
link
-function 的第二个参数是 element.如果您尝试注入 $templateRequest
和 $compile
,则需要在构造函数中进行:
The second parameter to link
-function is element. If you´re trying to inject $templateRequest
and $compile
you need to do it in the constructor:
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) }]);
在处理像指令函数这样的工厂函数时,我建议使用函数.遵循这个结构:
I'd suggest using function when dealing with factory functions like the directive function. Following this structure:
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 );
这篇关于在 angular + typescript 中使用 templateRequest($templateRequest 不是函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!