2015-11-03 44 views
1

我有一個指令,需要顯示一定數量的圖像基於屏幕的寬度,但我已經注意到,當重複使用ng-repeat這個指令時,只有指令的最後一個實現按預期工作。我認爲這可能與調用$ apply()有關,但窗口重新調整大小不會觸發摘要,所以我需要爲了查看頁面上反映的更改。爲什麼只有最後這些重複的指令按預期工作?

我在控制檯中沒有收到任何錯誤。有什麼辦法可以解決這個問題嗎?

這是指令。

(function() { 

    'use strict'; 

    angular.module('xxxx') 
     .directive('xxx', xxx); 

    function xxxxx ($window, $timeout) { 
    return { 
     restrict: 'AE', 
     templateUrl: 'xxxx', 
     scope :{ 
     data : "=" 
     }, 
     link: function (scope, elem, attrs) { 

     scope.componentName = 'xxxxx'; 
     var pageWidth = window.innerWidth; 
     scope.resultLimit = scope.data.conferences.length; 

     scope.setResultLimit = function(){ 

      console.log('triggered'); 


      pageWidth = window.innerWidth; 
      if(pageWidth < 768){ 
       if(scope.data.conferences.length % 2 !== 0){ 
       console.log('Less than 768'); 
       scope.resultLimit = scope.data.conferences.length - 1; 
       } else{ 
       scope.resultLimit = scope.data.conferences.length; 
       } 
      } 
      if(pageWidth >= 768 && pageWidth < 1200){ 
       if(scope.data.conferences.length % 3 !== 0){ 
       console.log('Greater than 768 and less than 1200'); 
       scope.resultLimit = scope.data.conferences.length - (scope.data.conferences.length % 3); 
       } else{ 
       scope.resultLimit = scope.data.conferences.length; 
       } 
      } 
      if(pageWidth >= 1200){ 
       console.log('greater than 1200'); 
       if(scope.data.conferences.length % 5 !== 0){ 

       scope.resultLimit = scope.data.conferences.length - (scope.data.conferences.length % 5); 

       } else{ 
       scope.resultLimit = scope.data.conferences.length; 
       } 
      } 

      console.log(scope.resultLimit); 
      //scope.$apply(); 




     }; 

     window.onresize = function(event){ 
      scope.$apply(function(){ 
      scope.setResultLimit(); 
      }) 

     }; 

     scope.setResultLimit(); 

     } 
    }; 
    } 

})(); 

回答

2

您將要覆蓋在每一個後續指令初始化onresize事件處理(window.onresize屬性)。您需要將幾個事件與addEventListener方法綁定。所以它會是:

window.addEventListener('resize', function() { 
    scope.$apply(function() { 
     scope.setResultLimit(); 
    }); 
}); 
+0

謝謝,我沒有意識到有addEventListener和onresize方法的區別。 – lorless

+1

這是非常重要的區別,因爲'onresize'屬性只能註冊一個事件處理程序。 – dfsq

相關問題