36

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

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

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

我最大的努力是这样的:

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

}

它有效,但并不优雅。有没有更好的办法?

4

7 回答 7

36

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

模块.ts

import { MyComponent } from './MyComponent';

angular.module('myModule', [])
  .component('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
   }
}

装饰器.ts

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

export const Component = (options: ng.IComponentOptions) => {
  return controller => angular.extend(options, { controller });
};
于 2016-04-14T21:55:54.437 回答
34

我正在使用一个简单的 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 http://jsbin.com/jipacoxeki/edit?html,js,output

于 2016-03-02T16:08:00.820 回答
14

这是我使用的模式:

ZippyComponent.ts

import {ZippyController} from './ZippyController';

export class ZippyComponent implements ng.IComponentOptions {

    public bindings: {
        bungle: '<',
        george: '<'
    };
    public transclude: boolean = false;
    public controller: Function = ZippyController;
    public controllerAs: string = 'vm'; 
    public template: string = require('./Zippy.html');
}

ZippyController.ts

export class ZippyController {

    bungle: string;
    george: Array<number>;

    static $inject = ['$timeout'];

    constructor (private $timeout: ng.ITimeoutService) {
    }
}

Zippy.html

<div class="zippy">
    {{vm.bungle}}
    <span ng-repeat="item in vm.george">{{item}}</span>
</div>

main.ts

import {ZippyComponent} from './components/Zippy/ZippyComponent';

angular.module('my.app', [])
    .component('myZippy', new ZippyComponent());
于 2016-03-02T12:53:25.453 回答
9

我在同一个问题上苦苦挣扎,并将我的解决方案放在这篇文章中:

http://almerosteyn.github.io/2016/02/angular15-component-typescript

module app.directives {

  interface ISomeComponentBindings {
    textBinding: string;
    dataBinding: number;
    functionBinding: () => any;
  }

  interface ISomeComponentController extends ISomeComponentBindings {
    add(): void;
  }

  class SomeComponentController implements ISomeComponentController {

    public textBinding: string;
    public dataBinding: number;
    public functionBinding: () => any;

    constructor() {
      this.textBinding = '';
      this.dataBinding = 0;
    }

    add(): void {
      this.functionBinding();
    }

  }

  class SomeComponent implements ng.IComponentOptions {

    public bindings: any;
    public controller: any;
    public templateUrl: string;

    constructor() {
      this.bindings = {
        textBinding: '@',
        dataBinding: '<',
        functionBinding: '&'
      };
      this.controller = SomeComponentController;
      this.templateUrl = 'some-component.html';
    }

  }

  angular.module('appModule').component('someComponent', new SomeComponent());

}

于 2016-02-18T20:51:08.183 回答
7

我正在使用以下模式将 angular 1.5组件与打字稿一起使用

class MyComponent {
    model: string;
    onModelChange: Function;

    /* @ngInject */
    constructor() {
    }

    modelChanged() {
        this.onModelChange(this.model);
    }
}

angular.module('myApp')
    .component('myComponent', {
        templateUrl: 'model.html',
        //template: `<div></div>`,
        controller: MyComponent,
        controllerAs: 'ctrl',
        bindings: {
            model: '<',
            onModelChange: "&"
        }
    });
于 2016-02-17T15:56:20.130 回答
1

我相信一种好方法是使用angular-ts-decorators。有了它,您可以像这样在 AngularJS 中定义组件:

import { Component, Input, Output } from 'angular-ts-decorators';

@Component({
  selector: 'myComponent',
  templateUrl: 'my-component.html
})
export class MyComponent {
    @Input() todo;
    @Output() onAddTodo;

    $onChanges(changes) {
      if (changes.todo) {
        this.todo = {...this.todo};
      }
    }
    onSubmit() {
      if (!this.todo.title) return;
      this.onAddTodo({
        $event: {
          todo: this.todo
        }
      });
    }
}

然后使用以下方法将它们注册到您的模块中:

import { NgModule } from 'angular-ts-decorators';
import { MyComponent } from './my-component';

@NgModule({
  declarations: [MyComponent]
})
export class MyModule {}

如果您想查看一个使用它的真实应用程序的示例,您可以查看这个

于 2017-04-28T13:37:18.917 回答
1

我建议不要使用定制的解决方案,而是使用ng-metadata库。您可以在https://github.com/ngParty/ng-metadata找到它。像这样,您的代码与 Angular 2 最兼容。正如自述文件中所述

没有黑客。没有覆盖。生产就绪。

我只是在使用此处答案中的定制解决方案后进行了切换,但是如果您立即使用此库会更容易。否则,您将不得不迁移所有小的语法更改。一个例子是这里的其他解决方案使用语法

@Component('moduleName', 'selectorName', {...})

而 Angular 2 使用

@Component({
  selector: ...,
  ...
})

因此,如果您不ng-metadata立即使用,您将大大增加以后迁移代码库的工作量。

编写组件的最佳实践的完整示例如下

// hero.component.ts
import { Component, Inject, Input, Output, EventEmitter } from 'ng-metadata/core';

@Component({
  selector: 'hero',
  moduleId: module.id,
  templateUrl: './hero.html'
})
export class HeroComponent {

  @Input() name: string;
  @Output() onCall = new EventEmitter<void>();

  constructor(@Inject('$log') private $log: ng.ILogService){}

}

(从ng-metadata recipies复制)

于 2017-02-08T20:51:55.883 回答