export function TariffMobileScrollDirectiveFactory() { return new TariffMobileDirective(); } class TariffMobileDirective implements angular.IDirective { restrict = 'A'; controllerAs = 'ctrl'; controller = TariffMobileController; scope = { onChange: "&", numberOfTariffs: "=", tariffIndex: "=" } bindToController = true; } export class TariffMobileController { public numberOfTariffs: number; public tariffIndex: number; public onChange: (config: any) => void; private currentTariff: number = 0; private tariffWidth: number; private screenWidth: number; private element: JQuery; static $inject = ["$element", "$scope"]; constructor($element: JQuery, $scope: ng.IScope) { this.element = $element; $scope.$watch(()=> this.tariffIndex, () => { if (this.currentTariff !== this.tariffIndex) { if (!this.tariffWidth) { this.setScreenSizes(); } this.element[0].scrollLeft = (this.tariffWidth * (this.tariffIndex+1)) - this.screenWidth; } }); this.element.bind('scroll', (event: JQueryEventObject) => { if (!this.tariffWidth) { this.setScreenSizes(); } let scrollPositonIndex = Math.round((this.element[0].scrollLeft + this.screenWidth) / this.tariffWidth)-1; if (this.currentTariff !== scrollPositonIndex) { this.currentTariff = scrollPositonIndex; this.onChange({ currentTariff: this.currentTariff }); } }); } private setScreenSizes() { this.tariffWidth = this.element[0].scrollWidth / this.numberOfTariffs; this.screenWidth = this.element[0].clientWidth; } }