2017-02-20 36 views
1

我在ng-repeat完成後嘗試在Typescript中製作Angular指令時出現問題。ng-repeat後的Typescript中的Angular指令

這是我正在努力使該指令工作:

export interface ILightSliderInitDirectiveScope extends ng.IScope { 
} 
export class LightSliderInitDirective implements ng.IDirective { 
    public static DirectiveName: string = "lightSliderInit"; 
    link = (scope: ILightSliderInitDirectiveScope, $element: any, attrs: ng.IAttributes) => { 
     if (scope.$watch('$scope.$last')) 
      scope.$emit('ngRepeatFinished'); 
    } 
} 

在控制器我有這樣的方法:

_self.$scope.$on('ngRepeatFinished', function() {...}); 

,並在HTML:

<li ng-repeat="it in items" light-slider-init>...</li> 

問題在於該指令有效,但它在的每次迭代中進入if條件210。

我該如何解決這個問題?

+0

我不知道,你應該有任何「迭代」,可能與NG重複發生有關。它的所有元素都應該在單個摘要循環中呈現,因此對於任何正常使用,您應該將其視爲單個原子操作。你爲什麼要這個活動?你打算如何使用它? –

+0

我想使用列表中的所有元素執行一個方法來使用lightslider插件。 http://sachinchoolur.github.io/lightslider/examples.html – Calde8

+0

試試這個http://stackoverflow.com/a/30257914/1299394 –

回答

0

scope.$watch爲此聽衆返回註銷功能,因此scope.$watch('whatever')始終是真的。並且您不應將$scope添加到觀看的表達式,因爲它將根據$scope對象進行評估。
這裏是你的代碼應該是這樣的:

scope.$watch('$last', $last => { 
    if ($last) scope.$emit('ngRepeatFinished'); 
}) 
0

我不會推薦點火和事件要做到這一點,因爲這使得它非常困難,如果您需要在頁面上2個或更多的光滑塊。

因爲這是在ng-repeat,你的鏈接函數將實際運行在中繼器的每個實例。因此,您應該在中繼器的最後一個項目上執行代碼,而不是$watch的值$last。基於https://stackoverflow.com/a/30257914/1299394

代碼:

export class LightSliderInitDirective implements ng.IDirective { 
    restrict: 'A', 
    link: function(scope: ILightSliderInitDirectiveScope, element: JQuery, attrs) { 
     if (scope.$last) { 
      // This is the last item in the repeater 
      // Instead of firing an event, just initialize the light gallery right here. 
      element.parent().lightGallery(); 
     } 
    } 
};