我在 angularjs 中创建了指令来调整 angularjs 中的图像大小。
这是指令的代码:
app.directive('resize1', function ($window) {
return {
restrict: 'A',
replace: true,
scope: {
params: '&',
path: '=',
siteurl: '='
},
link: function($scope, element, attrs) {
$scope.resizeImage = function() {
var size = 0;
var width = angular.element($window).width();
src = $(element).attr('src');
if (src != null || src != '') {
var url = parse_url(src).query;
var path = parse_url(src).path;
var str = url.split('&');
var link = '?';
$.each(str, function(index, value) {
pair = value.split('=');
if (pair[0] != 'h' && pair[0] != 'w') {
link = link + value + '&';
}
});
if (width >= 960) {
size = $scope.$eval($scope.params).gt960;
newWidth = size.w;
newHeight = size.h;
} else if (width < 960 && width >= 480) {
size = $scope.$eval($scope.params).bt480960;
newWidth = size.w;
newHeight = size.h;
} else {
size = $scope.$eval($scope.params).lt480;
newWidth = size.w;
newHeight = size.h;
}
link = link + 'h=' + newHeight + '&w=' + newWidth;
$(element).attr('src', path + link);
$(element).attr('ng-src', path + link);
$(element).closest('div.spinner').css({
'height' : newHeight,
'width' : newWidth,
'margin' : '0px auto'
});
}
};
angular.element($window).bind('resize', function() {
$scope.resizeImage();
});
$scope.$watch('path', function (){
//alert('df');
$scope.resizeImage();
});
}
}
});
我的html是:
<div class="list-view" ng-hide="productDetail == null">
<div class="list-view-img">
<div class="spinner">
<img resize1
ng-src="{{siteurl}}thumbnails/index?file={{path}}&h=200&w=200"
params="{lt480: {h: 300,w: 300}, bt480960: {h: 450,w: 450}, gt960: {h: 940,w: 940}}"
path="paths.products.primary_image + productDetail.primary_image"
siteurl="siteUrl"
/>
</div>
</div>
</div>
现在的问题是它的工作正常,但指令函数被调用了 3 次。有人能告诉我有什么问题吗?为什么它被称为三次,虽然我已经调用过一次?