在Typescript中创建AngularJS 1.5组件的最佳实践是什么? [英] What is best practice to create an AngularJS 1.5 component in Typescript?

查看:86
本文介绍了在Typescript中创建AngularJS 1.5组件的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Angular 1.5中的.component()语法.

I am experimenting with the .component() syntax in Angular 1.5.

最新的方式似乎是在组件中而不是在单独的文件中内联编码控制器,并且鉴于组件样板很小,我可以看到这种优势.

It seems that the latest fashion is to code the controller in-line in the component rather that in a separate file, and I can see the advantage of that given that the component boilerplate is minimal.

问题是我已经将我的控制器编码为打字稿类,并希望继续这样做,因为这似乎与Angular2保持一致.

The problem is that I having been coding my controllers as typescript classes and would like to continue doing so because that seems to be consistent with Angular2.

我最大的努力是这样的:

My best effort is something like this:

export let myComponent = {
  template: ($element, $attrs) => {
    return [
      `<my-html>Bla</my-html>`
    ].join('')
  },
  controller: MyController
};
class MyController {

}

它可以工作,但是不优雅.有更好的方法吗?

It works, but it's not elegant. Is there a better way?

推荐答案

如果您想完全采用Angular 2方法,则可以使用:

If you wanted to completely adopt an Angular 2 approach, you could use:

module.ts

import { MyComponent } from './MyComponent';

angular.module('myModule', [])
  .component('myComponent', MyComponent);

MyComponent.ts

import { Component } from './decorators';

@Component({
  bindings: {
    prop: '<'
  },
  template: '<p>{{$ctrl.prop}}</p>'
})
export class MyComponent {

   prop: string;

   constructor(private $q: ng.IQService) {}

   $onInit() {
     // do something with this.prop or this.$q upon initialization
   }
}

decorators.ts

/// <reference path="../typings/angularjs/angular.d.ts" />

export const Component = (options: ng.IComponentOptions) => {
  return controller => angular.extend(options, { controller });
};

这篇关于在Typescript中创建AngularJS 1.5组件的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆