加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Typescript中创建AngularJS 1.5组件的最佳实践是什么?

发布时间:2020-12-17 08:32:22 所属栏目:安全 来源:网络整理
导读:我正在试验.component()语法在Angular 1.5。 看来最新的方式是在组件中在线编写控制器,而不是在一个单独的文件中,我可以看到,组件样板是最小的优点。 问题是,我已经编写我的控制器作为typescript类,并希望继续这样做,因为这似乎与Angular2一致。 我最
我正在试验.component()语法在Angular 1.5。

看来最新的方式是在组件中在线编写控制器,而不是在一个单独的文件中,我可以看到,组件样板是最小的优点。

问题是,我已经编写我的控制器作为typescript类,并希望继续这样做,因为这似乎与Angular2一致。

我最大的努力是这样:

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

}

它工作,但它不优雅。有没有更好的办法?

我使用一个简单的Typescript装饰器来创建组件
function Component(moduleOrName: string | ng.IModule,selector: string,options: {
  controllerAs?: string,template?: string,templateUrl?: string
}) {
  return (controller: Function) => {
    var module = typeof moduleOrName === "string"
      ? angular.module(moduleOrName)
      : moduleOrName;
    module.component(selector,angular.extend(options,{ controller: controller }));
  }
}

所以我可以使用它像这样

@Component(app,'testComponent',{
  controllerAs: 'ct',template: `
    <pre>{{ct}}</pre>
    <div>
      <input type="text" ng-model="ct.count">
      <button type="button" ng-click="ct.decrement();">-</button>
      <button type="button" ng-click="ct.increment();">+</button>
    </div>
  `
})
class CounterTest {
  count = 0;
  increment() {
    this.count++;
  }
  decrement() {
    this.count--;
  }
}

你可以试试一个工作jsbin here http://jsbin.com/jipacoxeki/edit?html,output

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读