如何在AngularJS控制器中在文档就绪时运行函数?
如何在AngularJS控制器中在文档就绪时运行函数?
我在我的Angular控制器中有一个函数,我想让这个函数在文档准备就绪时运行,但我注意到Angular在创建DOM时运行它。
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 }
有人知道我该如何处理吗?
admin 更改状态以发布 2023年5月24日
看看这个贴子:如何在页面加载时执行angular控制器函数?
以便快速查找:
// register controller in html // in controller $scope.init = function () { // check if there is query in url // and fire search in case its value is not empty };
这样,您就不必等到文档准备完成。
我们可以使用angular.element(document).ready()
方法来为文档准备好时附加回调函数。我们可以像这样在控制器中简单地附加回调:
angular.module('MyApp', []) .controller('MyCtrl', [function() { angular.element(document).ready(function () { document.getElementById('msg').innerHTML = 'Hello'; }); }]);