【发布时间】:2013-06-05 19:15:01
【问题描述】:
我需要以实际大小显示图像,即使它比容器大。我尝试了使用 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;
}
}]);
此脚本有效,但如果图像很大,则仅在多次单击按钮后才有效。
我应该怎么做才能让它一键运行?
还有比这更好的发现图像大小的方法吗?
【问题讨论】:
-
将代码移动到指令中 - 不要尝试在控制器内调用 onload 函数 - 在此处阅读最佳实践:docs.angularjs.org/misc/faq#dommanipulation
-
@callmekatootie 你能详细说明一下吗?为什么将 onload 移动到指令更好?
标签: angularjs