Update DIV element after loading image using Angular JS

与世无争的帅哥 提交于 2019-12-12 16:24:44

问题


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:


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



来源:https://stackoverflow.com/questions/35220107/update-div-element-after-loading-image-using-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!