Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 395
pawelforums Avatar asked Aug 12 '26 00:08

pawelforums


1 Answers

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

like image 103
vp-platform Avatar answered Aug 13 '26 14:08

vp-platform



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!