在angular.js实际大小显示图像 [英] Display image in its actual size in angular.js

查看:178
本文介绍了在angular.js实际大小显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在其实际尺寸以显示图像,即使它是比它的容器大。我试着用图片变量并像这样捕捉负载大小的技巧:

I need to display an image in its actual size, even if it is bigger than its container. I tried the trick of using Image variable and capturing the size on load with something like this:

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:

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;
    }
}]);

本脚本工作,但按钮被点击后,才数次如果图像是很大的。

This script works, but only after the button is clicked several times if the image is big.

我应该怎么做才能让它在点击工作?

What should I do to make it work in one click?

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

Is there a better way to discover the image size than this?

推荐答案

您需要使用的 $范围。$适用 ,否则不进行任何更改为 $范围角事件处理程序将无法被正确处理:

You need to use $scope.$apply, otherwise any changes to $scope made in non-Angular event handlers won't be processed properly:

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

这篇关于在angular.js实际大小显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆