如何在文档准备好时在 AngularJS 控制器中运行函数? [英] How to run function in AngularJS controller on document ready?
本文介绍了如何在文档准备好时在 AngularJS 控制器中运行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 angular 控制器中有一个函数,我希望这个函数在文档就绪时运行,但我注意到 angular 在创建 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屋!
查看全文