TypeError:$ compile不是函数

时间:2017-06-21 14:09:19

标签: javascript angularjs typescript

我在typescript中写了一个AngularJS指令。这是我的代码,在浏览器错误中抛出这样的 TypeError:$ compile不是compileComponent.js上的函数:14

但是TS编译器没有显示任何错误。

module dashboard {
  function CompileComponent($compile): ng.IDirective {
    console.log('Compiler s--');

    return {
      replace: false,
      restrict: 'EA',
      link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModel: any) => {
        scope.$watch(
          function (scope) {
            return scope.$eval(attrs.compile);
          },
          function (value) {
            element.html(value);
            $compile(element.contents())(scope);
          }
        );
      }
    }
  }
  var dragdropModule = angular.module('dashboard');
  dragdropModule.directive("compileComponent", [CompileComponent]);
}

2 个答案:

答案 0 :(得分:1)

尝试实现它:

 class CompileComponent implements ng.IDirective {
        restrict = 'A';
        require = 'ngModel';
        templateUrl = 'myDirective.html';
        replace = true;
enter code here
    link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => {
 // do something
}

static factory(): ng.IDirectiveFactory {
    const directive = ($compile: ng.ICompileService) => new CompileComponent($compile);
    directive.$inject = ['$compile'];
    return directive;
}
        constructor(private $compile: ng.ICompileService) {
        }
     }
    app.directive('compileComponent', CompileComponent.factory());

答案 1 :(得分:0)

我得到了我做错了什么,我忘了在

中注入$ compile
dragdropModule.directive("compile", ["$compile", CompileComponent]);