我有一个指令,需要根据屏幕的宽度显示一定数量的图像,但我注意到,当使用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();
}
};
}
})();
答案 0 :(得分:2)
您在每个下一个指令初始化中覆盖onresize
事件处理程序(window.onresize
属性)。您需要使用addEventListener
方法绑定多个事件。所以它将是:
window.addEventListener('resize', function() {
scope.$apply(function() {
scope.setResultLimit();
});
});