使用Angular JS加载图像后更新DIV元素 [英] Update DIV element after loading image using Angular JS

查看:127
本文介绍了使用Angular JS加载图像后更新DIV元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是更新用于图像容器的div元素(宽度和高度)。问题是视图和控制器被调用的速度比加载图像要快得多,当它最终被调用时,视图已经被渲染,我不能再设置宽度和高度了。也许我的做法是完全错误的......也许我应该选择别的东西......这是我的测试代码,你可以检查并理解我想做的事情:

 < 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。高度;
scope.my_id =testing;
});
}
};
});

这是jsfiddle:



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



顺便说一下。我只在启动时在页面上添加一次图像。

解决方案

添加范围。$ apply( ); 在你的指令中:



编辑的JsFiddle:



http://jsfiddle.net/vmeaseag/



事实上,检查Angular文档: $ rootScope.Scope


$ apply()用于从角度框架
之外的角度执行角度表达式。 (例如,来自浏览器DOM事件,
setTimeout,XHR或第三方库)。


或更好: https://docs.angularjs.org/guide/scope#scope-life-cycle


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.

解决方案

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

这篇关于使用Angular JS加载图像后更新DIV元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆