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

ワーキングプランク: http://plnkr.co/edit/HX0bWz?p=preview

于 2013-08-06T06:33:38.043 に答える