5

我需要以实际大小显示图像,即使它比它的容器大。我尝试了使用 Image 变量并使用以下方法捕获加载大小的技巧:

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

此脚本有效,但如果图像很大,则仅在多次单击按钮后才有效。

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

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

4

3 回答 3

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;
  });
}
于 2013-06-10T07:26:06.103 回答
2

根据指令“模式”重新构建整个事物可能还为时不晚。我对类似问题的解决方案(链接)得到了几票赞成,这让我认为这是传统方法。看看:

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

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

于 2013-08-06T06:33:38.043 回答
0

这对我有用(对课程使用 twitter bootstrap):

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

{
  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>
于 2014-10-29T21:13:53.847 回答