gpt4 book ai didi

angularjs - 在 angular.js 中以实际大小显示图像

转载 作者:行者123 更新时间:2023-12-04 17:50:47 25 4
gpt4 key购买 nike

我需要以其实际大小显示图像,即使它大于其容器。我尝试了使用 Image 变量和 capturing the size on load 的技巧。像这样:

HTML:

<div ng-controller="MyCtrl">
<input ng-model="imageurl" type="url" />
<button ng-click="loadimage()" type="button">Load Image</button>
<img ng-src="{{image.path}}"
style="width: {{image.width}}px; height: {{image.height}}px" />
</div>

Javascript:
.controller("MyCtrl", ["$scope", function ($scope) {
$scope.image = {
path: "",
width: 0,
height: 0
}
$scope.loadimage = function () {
var img = new Image();
img.onload = function () {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
}
img.src = $scope.imageurl;
}
}]);

这个脚本可以工作,但只有在图像很大的情况下单击按钮几次之后。

我应该怎么做才能让它一键运行?

有没有比这更好的方法来发现图像大小?

最佳答案

您需要使用 $scope.$apply , 否则对 $scope 的任何更改在非 Angular 事件处理程序中制作的将无法正确处理:

img.onload = function () {
$scope.$apply(function() {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
});
}

关于angularjs - 在 angular.js 中以实际大小显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17018685/

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