【问题标题】:Writing an Angular directive with a TypeScript class使用 TypeScript 类编写 Angular 指令
【发布时间】:2015-08-20 19:22:39
【问题描述】:

我可能只是试图一次组合太多“对我来说很陌生”的概念,但我正在尝试使用 TypeScript 类编写自定义 Angular 指令。目前,我并不想做任何非常有用的事情,只是一个 POC。

我有一个如下所示的 TypeScript 文件:

module App {
    'use strict';

    export class appStepper {

        public link:(scope:angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => void;
        public template:string = '<div>0</div><button>-</button><button>+</button>';
        public scope = {};
        public restrict:string = 'EA';

        constructor(){ }

        public static Factory(){
            var directive = () =>
            { return new appStepper(); };
            return directive;
        }
    }

    angular.module('app').directive('appStepper', App.appStepper.Factory());
}

它在 JavaScript 中编译成这样:

(function(App) {
    'use strict';
    var appStepper = (function() {
        function appStepper() {
            this.template = '<div>0</div><button>-</button><button>+</button>';
            this.scope = {};
            this.restrict = 'EA';
        }
        appStepper.Factory = function() {
            var directive = function() {
                return new appStepper();
            };
            return directive;
        };
        return appStepper;
    })();
    App.appStepper = appStepper;
    angular.module('app').directive('appStepper', App.appStepper.Factory());
})(App || (App = {}));

我的角度模块看起来像(我什至不知道我是否需要这样做):

angular.module('app',['appStepper'])

我尝试在我的观点中使用它:

<div app-stepper></div>

并得到这些错误:

 Uncaught Error: [$injector:nomod] 
 Uncaught Error: [$injector:modulerr] 

为什么我的app 不知道我的指令?

【问题讨论】:

  • 应该是angular.module('app', [])
  • 很高兴知道!但它仍然给我留下了同样的问题。
  • 检查这个,有详细的解释和工作 plunker stackoverflow.com/a/30506888/1679310
  • @RadimKöhler - 在遵循这个例子之后,我发现成功了!谢谢分享。

标签: javascript angularjs typescript angular-directive


【解决方案1】:

虽然这不是同一个问题,但这个答案包括我正在尝试做的一个例子:How can I define my controller using TypeScript?

我按照它引用的 Plnkr 中的示例进行操作,发现成功:http://plnkr.co/edit/3XORgParE2v9d0OVg515?p=preview

我的最终 TypeScript 指令如下所示:

module App {
    'use strict';

    export class appStepper implements angular.IDirective {

        public link:(scope:angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => void;
        public template:string = '<div>0</div><button>-</button><button>+</button>';
        public scope = {};
        public restrict:string = 'EA';

        constructor(){ }

    }

    angular.module('app').directive('appStepper', [() => new App.appStepper()]);
}

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 2015-12-01
    • 2015-08-28
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2016-07-02
    • 2017-02-14
    相关资源
    最近更新 更多