角度2管道/过滤器与组件变量

时间:2016-02-28 10:29:35

标签: javascript angularjs angular

我有应用程序,显示来自此和下周的事件。周由两个按钮切换。我需要过滤器/管道,它只显示当前活动周的事件。我在Angular 1中有这个过滤器,一切正常,但在An 2中,我无法使这个过滤器工作。见代码:

    @Page({
    templateUrl: 'build/pages/lunches/lunches.html',
    providers: [LunchService, HTTP_PROVIDERS],
})

export class Lunches {
    weekDuration:number = 24 * 60 * 60 * 7 * 1000;
    timestampFix:number = 24 * 60 * 60 * 4 * 1000;

    currentWeekNumber:number = parseInt(new Date().getTime() / this.weekDuration);
    nextWeekNumber:number = this.currentWeekNumber + 1;
    activeWeekNumber:string = '2408';
    lunches:Array;
    activeLunches:Array;
    noData:boolean = true;

    constructor(private lunchService:LunchService) {
    }

    ngOnInit() {
        this.loadLunches();
    }

    loadLunches() {
        this.lunchService.getLunchList().subscribe(
            data => {
                var lunches = data;
                lunches.forEach((item, index) => {
                    lunches[index].date = new Date(item.date);
                });
                this.lunches = lunches;
                this.weekFilter();
            }
        );
    }

    weekFilter() {
        var activeLunches = [];
        this.lunches.forEach((item, index) => {
            var lunchDate = new Date(item.date).getTime() - this.timestampFix;
            console.log(this.currentWeekNumber, ' = ', parseInt(lunchDate / this.weekDuration));
            if (this.activeWeekNumber == parseInt(lunchDate / this.weekDuration)) {
                this.noData = false;
                activeLunches.push(item);
            }
        });
        this.activeLunches = activeLunches;
    }
}

模板:

<div padding>
    <ion-segment [(ngModel)]="activeWeekNumber" (click)="weekFilter()">
        <ion-segment-button value="{{currentWeekNumber}}" selected>
            This week
        </ion-segment-button>
        <ion-segment-button value="{{nextWeekNumber}}">
            Next
        </ion-segment-button>
    </ion-segment>
</div>
<ion-card *ngIf="noData">
    <ion-card-content>
        No lunches for this week.
    </ion-card-content>
</ion-card>
<ion-card *ngFor="#lunch of activeLunches">
    <ion-card-header>
        <h2>{{lunch.date | date: "E d. M."}}</h2>
    </ion-card-header>
</ion-card>

这是我的实际代码不能正常工作,我认为它的解决方案不好。我尝试将其写为管道,但我无法访问和更改变量noData。

编辑:根据评论,我决定使用这个解决方案,但是每当activeWeekVariable改变时,每次触发weekFilter函数都有问题。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

时收到通知
myArray

改变有不同的方式。

  • 您可以将字段更改为getter / setter
activeWeekNumber:string = '2408';
  • 或使用ngModel中的事件
_activeWeekNumber:string = '2408';
get activeWeekNumber():string {
  return this._activeWeekNumber;
}
set activeWeekNumber(value:string) {
  this._activeWeekNumber = value;
}