我的控制器中定义了一个范围函数,它调用API从数据库中获取数据。我在ng-repeat中使用这个范围函数。但是当我运行应用程序时,它正在被绞死。
查看:
<div class="col-xs-4 product-padding" ng-repeat="product in productList | filter:query | orderBy:'name'| offset: currentPage*itemsPerPage | limitTo: itemsPerPage " ng-cloak>
<div class="theme-04-scope">
<div class="thumbnail">
<small class="defaultImageSize" ng-if="checkImageAttribute(product.ItemAttributes) == true">
<img class="ui-corner-all img-responsive defaultImageSize" ng-src="data:image/jpeg;base64,{{loadProductImage(product.ItemAttributes)}}" />
@*ng-src="/Product/LoadProductImage/{{loadProductImage(product.ItemAttributes)}}?width=200&height=144"*@
</small>
</div>
</div>
</div>
Angularjs控制器:
// Get product image.
$scope.loadProductImage = function (itemAttributes) {
var imageId = 0;
$.each(itemAttributes, function (index, data) {
if (data.AttributeId == 1000700 && data.DataXml != null) {
imageId = data.DataXml;
return false;
}
});
productRepository.getProductImage(imageId, 200, 144).then(function (imageArrary) {
$scope.itemIdArr.push(imageId);
$scope.productImage = imageArrary;
});
return $scope.productImage;
}
存储库功能:
getProductImage: function (imageId, width, height) {
var deferred = $q.defer();
$http.post('/Product/LoadProductListImage', JSON.stringify({ id: imageId, width: width, height: height })).success(deferred.resolve).error(deferred.reject);
return deferred.promise;
}
答案 0 :(得分:1)
当您在视图插值中放置一个函数时,它会在每个摘要周期至少评估两次,这可能是每秒多次。因此,将API调用放入其中一个函数中并不是一个好主意。
.directive('getProductImage', function ($http) {
return {
scope: {
imageId: '@imageId',
width: '@width',
height: '@height'
},
link: function (scope, element, attrs) {
console.info(scope.imageId, scope.width, scope.height)
$http.post('/Product/LoadProductListImage', JSON.stringify({ id: scope.imageId, width: scope.width, height: scope.height })).success(function (data) {
scope.imageArrr = data;
});
},
template: '<img class="ui-corner-all img-responsive defaultImageSize" ng-src="data:image/jpeg;base64,{{imageArrr}}"></img>'
}
});
...会在您的视图中显示如下内容:
<span get-product-image width="200" image-id="200" height="144"></span>
享受..