在 AngularJS 完成渲染 HTML 后运行 jQuery 代码 [英] Run jQuery code after AngularJS completes rendering HTML

查看:24
本文介绍了在 AngularJS 完成渲染 HTML 后运行 jQuery 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器中,我使用 $http 或 $resource 服务获取一些 JSON 数据.然后我将这些数据写入 $scope 并且 AngularJS 更新页面的 HTML 结构.我的问题是我需要知道用 Angular ng-repeat 指令填充的列表(我的意思是 HTML DOM 元素)的新大小(宽度和高度)是多少.因此,我必须在 Angular 完成更新 DOM 结构后立即运行 javascript 代码.什么是正确的方法呢?在过去的四个小时里,我在互联网上搜索过,但找不到任何解决我问题的方法.

In controller I get some JSON data using $http or $resource services. Then I write this data in $scope and AngularJS updates HTML structure of the page. My problem is that I need to know what is the new size (width and height) of the list (I mean, HTML DOM element) that is filled with Angular ng-repeat directive. Consequently, I have to run javascript code right after Angular finishes updating DOM structure. What is the proper way to do it? I have searched internet over the last four hours but I couldn't find any solution to my problem.

这是我接收 JSON 数据的方式:

This is how I receive JSON data:

var tradesInfo = TradesInfo.get({}, function(data){
    console.log(data);
    $scope.source.profile = data.profile;
            $scope.trades = $scope.source.profile.trades;
        $scope.activetrade = $scope.trades[0];
        $scope.ready = true;


    init();  //I need to call this function after update is complete

});

这就是 init() 函数中发生的事情:

And this is what happens in init() function:

function init(){
    alert($('#wrapper').width());
    alert($('#wrapper').height());
}

我知道一定有什么方法可以轻松解决这个问题,但我现在找不到它.提前致谢.

I know that there must be something easy to solve this problem but I can't just find it now. Thanks in advance.

推荐答案

其实在这种情况下,angular 的方式并不是简单的方式,而是唯一正确的方式 :)

Actually in this case the angular way is not the easy way but the only right way :)

您必须编写一个指令并附加到您想知道其高度的元素.并且从控制器您 $broadcast 一个事件,指令将捕获该事件,然后您就可以进行 DOM 操作.永远不要在控制器中.

You have to write a directive and attach to the element you want to know the height of. And from the controller you $broadcast an event, the directive'll catch the event and there you can do the DOM manipulation. NEVER in the controller.

var tradesInfo = TradesInfo.get({}, function(data){
    console.log(data);
    $scope.source.profile = data.profile;
    ...

    $scope.$broadcast('dataloaded');
});


directive('heightStuff', ['$timeout', function ($timeout) {
    return {
        link: function ($scope, element, attrs) {
            $scope.$on('dataloaded', function () {
                $timeout(function () { // You might need this timeout to be sure its run after DOM render.
                    element.width()
                    element.height()
                }, 0, false);
            })
        }
    };
}]);

这篇关于在 AngularJS 完成渲染 HTML 后运行 jQuery 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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