pawelforums
pawelforums

Reputation: 35

Update DIV element after loading image using Angular JS

My goal is to update the div element (its width and height) that is used for a container for my image. Problem is that view and controllers are called much faster then image is loaded, and when it is finally called, the view is already rendered and I can not set width and height anymore. Maybe my approach is completely wrong... Maybe I should go with something else... Here is my test code that you can check and understand what I want to do:

<div ng-controller="c">
   <div id={{my_id}} width={{widthOfOutsideWrapper}} height={{heightOfOutsideWrapper}}>
       <img ng-src="{{src}}" imageonload />
   </div>
</div>

....

app.controller('c', function($scope) {
    $scope.src ="https://www.google.com.ua/images/srpr/logo4w.png";
});

...

app.directive('imageonload', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                alert('image is loaded');
                scope.widthOfOutsideWrapper= this.width;
                scope.heightOfOutsideWrapper= this.height;
                scope.my_id = "testing";
            });
        }
    };
});

Here is jsfiddle:

http://jsfiddle.net/2CsfZ/855/

Btw. I only add image once on page when it is started.

Upvotes: 3

Views: 1190

Answers (1)

vp-platform
vp-platform

Reputation: 601

Add a scope.$apply(); in your directive:

Edited JsFiddle:

http://jsfiddle.net/vmeaseag/

In fact, check the Angular docs: $rootScope.Scope

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

or better here: https://docs.angularjs.org/guide/scope#scope-life-cycle

Upvotes: 4

Related Questions