以angular.js显示其实际大小的图像

时间:2013-06-10 07:19:47

标签: angularjs

我需要以实际尺寸显示图像,即使它比容器大。我尝试了使用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;
    }
}]);

此脚本有效,但只有在图像很大的情况下多次单击按钮后才能使用。

我应该怎么做才能让它一键完成?

有没有比这更好的方法来发现图像尺寸?

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

根据指令“模式”重建整件事可能还为时不晚。我对类似问题的解决方案(link)得到了几个上升票,这让我觉得这是传统方法..看看:

HTML:
    <div ng-controller="MyCtrl">
        <input ng-model="image.tmp_path" type="url" />
        <button ng-click="loadimage()" type="button">Load Image</button>
        <img ng-src="{{image.path}}" preloadable />
    </div>

CSS:
    img[preloadable].empty{
        width:0; height:0;
    }

    img[preloadable]{
        width:auto; height:auto;
    }

JS:
    // Very "thin" controller:
    app.controller('MyCtrl', function($scope) {
       $scope.loadimage = function () {
            $scope.image.path = $scope.image.tmp_path;
       }
    });

    // View's logic placed in directive 
    app.directive('preloadable', function () {        
       return {
          link: function(scope, element) {
             element.addClass("empty");
             element.bind("load" , function(e){
                element.removeClass("empty");
             });
          }
       }
    });

工作插件:http://plnkr.co/edit/HX0bWz?p=preview

答案 2 :(得分:0)

这对我有用(使用twitter引导程序):

mainfile.js文件(在产品数组中):

{
  name: 'Custom Products',
  size: {width: 15, height: 15},      
  images:{thumbnail:"img/custom_products/full_custom_3.jpg"}
}

index.html文件:

      <div class="gallery">
        <div class="img-wrap">
            <ul class="clearfix">
                <li class="small-image pull-left thumbnail">
                    <img ng-src="{{product.images.thumbnail}}" style="height:{{product.size.height}}em; width: {{product.size.width}}em" />
                </li>
          </ul>
        </div>
      </div>
相关问题