如何在准备好文档的AngularJS控制器中运行函数? [英] How to run function in AngularJS controller on document ready?

查看:83
本文介绍了如何在准备好文档的AngularJS控制器中运行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角度控制器中有一个函数,我希望可以在准备就绪的文档上运行此函数,但是我注意到在创建dom时,角度函数会运行它.

I have a function within my angular controller, I'd like this function to be run on document ready but I noticed that angular runs it as the dom is created.

 function myController($scope)
 {
     $scope.init = function()
     {
        // I'd like to run this on document ready
     }

     $scope.init(); // doesn't work, loads my init before the page has completely loaded
 }

有人知道我该怎么做吗?

Anyone know how I can go about this?

推荐答案

我们可以使用angular.element(document).ready()方法为文档准备就绪时附加回调.我们可以像这样简单地将回调附加到控制器中:

We can use the angular.element(document).ready() method to attach callbacks for when the document is ready. We can simply attach the callback in the controller like so:

angular.module('MyApp', [])

.controller('MyCtrl', [function() {
    angular.element(document).ready(function () {
        document.getElementById('msg').innerHTML = 'Hello';
    });
}]);

http://jsfiddle.net/jgentes/stwyvq38/1/

这篇关于如何在准备好文档的AngularJS控制器中运行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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