簡體   English   中英

單獨的指令范圍Angular2

[英]Separate Directive Scope Angular2

我曾嘗試在此處查看一些類似的問題,但是找不到解決我的問題的方法。

@Directive()有一個倒數計時,可以接收幾個輸入並倒數。 倒數計時部分有效,但我遇到一個問題,即所有選擇器在進入下一個倒數計時之前正在運行/發出相同的數字。 如何讓他們使用自己的參數分別倒計時並同時運行?

普倫克

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);
    }
}

問題出在您的組件上。 您對所有3個指令使用了相同的變量“計數”。

如果您使用3個不同的組件級變量,則它會起作用,如下所示:

這是您的pl子的更新版本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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM