angularjs - 使用 Angular JS 加载图像后更新 DIV 元素

标签 angularjs image updates onload directive

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

<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";
            });
        }
    };
});

这是 jsfiddle:

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

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

最佳答案

在你的指令中添加一个 scope.$apply();:

编辑的 JsFiddle:

http://jsfiddle.net/vmeaseag/

事实上,查看 Angular 文档:$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).

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

关于angularjs - 使用 Angular JS 加载图像后更新 DIV 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35220107/

相关文章:

ios - 组合 View Controller ?或具有多个部分的 TableViewController?

iphone - iOS 企业应用 : How to roll out updates?

css - Angular Material 垂直 slider

javascript - 使用 angular js 有条件地显示 HTML,但是当我将 HTML 代码放在 ng-if 或 ng-switch 语句中时,CSS 被弄乱了

c# - 如何在 Visual Studio 2010 的数据库中包含图像

html - 将图像居中并使其适合网站的屏幕(非常简单)

javascript - 如何使用按钮栏作为 ionic 导航选项卡

javascript - 从谷歌地图检索坐标

.net - 如何在不写程序集名称的情况下设置 WPF 图像源?

mysql - 使用另一个表中的 ID 连接和更新 MySQL 记录?