gpt4 book ai didi

javascript - Angular - Controller 中的图像加载事件

转载 作者:行者123 更新时间:2023-12-03 08:38:38 24 4
gpt4 key购买 nike

我需要从网络(动态)加载的图像的尺寸来适应我的显示。所以我需要在 Controller 中使用 onload 事件( View 尚未渲染),如下所示:

.controller("MyCtrl", function($scope){
img.onload = function () {
// $scope changes not effective
}

我知道我可以使用$apply,但我不是它的忠实粉丝,因为它会损害性能。您是否有其他我可以使用的解决方案,无论是让 Angular 了解我在做什么(img.onload 不是这种情况),还是让范围考虑我的更改?

谢谢!

最佳答案

您需要使用指令来获取图像属性,并将它们分配给 Controller 中的范围。这是一些伪代码,不能保证它 100% 开箱即用,但它应该让您了解需要发生什么。

模板

<div ng-controller="MyCtrl">
<img img-size src="..." />
</div>

指令

.directive('imgSize', function() {
return {
link: function (scope, elem, attrs) {
elem.on('load', function(e) {
var width = $(this).width();
var height: $(this).height();

scope.$evalAsync(function() {
scope.imageWidth = width;
scope.imageHeight = height;
});
});
}
}
});

关于javascript - Angular - Controller 中的图像加载事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33120809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com