单独的指令范围Angular2

时间:2016-08-29 18:24:24

标签: javascript angular

我曾尝试在SO处查看类似的问题,但无法找到解决问题的方法。

倒计时@Directive()会输入几个输入并倒计时。倒计时部分有效,除了我遇到一个问题,所有的选择器都在运行/发出相同的数字然后进入下一个倒计时。如何使用自己的参数单独倒计时并同时运行?

Plunkr

app.component.ts中的

run()代码

run() {
    var _this = this;
    clearInterval(_this._timer);
    var counting = 0;
    var incrementFactor = 0;
    var increment = 1;

    if (!isNaN(_this._duration) && !isNaN(_this._step) && !isNaN(_this._countFrom) && !isNaN(_this._countTo)) {
        counting    = Math.round(_this._countFrom);
        incrementFactor = Math.round(Math.abs(_this._countTo - _this._countFrom) / ((_this._duration * 1000) / _this._step));
        increment       = (incrementFactor < 1) ? 1 : incrementFactor

        _this.countToChange.emit(counting);

        _this._timer = setInterval(function() {
            if (_this._countTo < _this._countFrom) {
                if (counting <= _this._countTo) {
                    clearInterval(_this._timer);
                    _this.countToChange.emit(_this._countTo);
                } else {
                    _this.countToChange.emit(counting);
                    counting -= increment;
                }
            }
        }, _this._step);
    }
}

1 个答案:

答案 0 :(得分:1)

问题在于您的组件。你使用了相同的变量&#39; count&#39;对于所有3个指令。

如果您使用3个不同的组件级别变量,它可以工作,如下所示:

这是您的插件的更新版本 https://plnkr.co/edit/PrwF8gYrl5AYCB0XcUsg?p=preview

@Component({
    selector: 'my-app',
    template: `
    <countDown [step]="100" [countFrom]="100" [countTo]=0 [duration]="2" (countToChange)="count1 = $event">{{ count1 }}</countDown>
    <countDown [step]="100" [countFrom]="1000" [countTo]=0 [duration]="4" (countToChange)="count2 = $event">{{ count2 }}</countDown>
    <countDown [step]="100" [countFrom]="10000" [countTo]=0 [duration]="20" (countToChange)="count3 = $event">{{ count3 }}</countDown>
    `,
    directives: [countDown]
})
export class AppComponent {
  public count1:number;
  public count2:number;
  public count3:number;
}
相关问题