3

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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Correct answer but a bit short. Try to flesh out the answer a bit with some description of why $apply() is needed here.
Thanks for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.