Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image in its actual size in angular.js

Tags:

angularjs

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:

.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?

like image 214
Endy Tjahjono Avatar asked Jun 10 '13 07:06

Endy Tjahjono


2 Answers

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;
  });
}
like image 178
robertklep Avatar answered Oct 10 '22 06:10

robertklep


May be it is still not late to re-build whole thing according to directives "pattern". My solution for similar problem ( link ) got several up-votes and it causes me to think that it is conventional approach.. Have a look:

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

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

like image 45
Ivan Chernykh Avatar answered Oct 10 '22 06:10

Ivan Chernykh