为什么只有最后一个重复的指令按预期工作?

时间:2015-11-03 16:19:51

标签: angularjs angularjs-directive

我有一个指令,需要根据屏幕的宽度显示一定数量的图像,但我注意到,当使用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();

      }
    };
  }

})();

1 个答案:

答案 0 :(得分:2)

您在每个下一个指令初始化中覆盖onresize事件处理程序(window.onresize属性)。您需要使用addEventListener方法绑定多个事件。所以它将是:

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