for*_*yez 249 javascript onload angularjs
我的角度控制器中有一个函数,我希望这个函数可以在文档准备好的情况下运行但我注意到角度在创建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
}
Run Code Online (Sandbox Code Playgroud)
谁知道我怎么能这样做?
Wil*_*ill 443
我们可以使用该angular.element(document).ready()方法为文档准备好时附加回调.我们可以简单地在控制器中附加回调,如下所示:
angular.module('MyApp', [])
.controller('MyCtrl', [function() {
angular.element(document).ready(function () {
document.getElementById('msg').innerHTML = 'Hello';
});
}]);
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/jgentes/stwyvq38/1/
vin*_*esh 29
看这篇文章如何在页面加载时执行角度控制器功能?
快速查找:
// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>
// in controller
$scope.init = function () {
// check if there is query in url
// and fire search in case its value is not empty
};
Run Code Online (Sandbox Code Playgroud)
这样,您不必等到文档准备就绪.
Wil*_*l M 22
Angular在
DOMContentLoaded事件时或在评估angular.js脚本时自动初始化,如果此时document.readyState设置为'complete'.此时,Angular会查找指定应用程序根目录的ng-app指令.
https://docs.angularjs.org/guide/bootstrap
这意味着控制器代码将在DOM准备好后运行.
因此它只是$scope.init().
Ale*_*ink 18
Angular有几个时间点来开始执行函数.如果你寻求类似jQuery的东西
$(document).ready();
Run Code Online (Sandbox Code Playgroud)
您可能会发现角度模拟非常有用:
$scope.$watch('$viewContentLoaded', function(){
//do something
});
Run Code Online (Sandbox Code Playgroud)
当您想要操作DOM元素时,这个很有用.它将在加载所有te元素后开始执行.
UPD:当您想要更改css属性时,上述内容有效.但是,当您想要测量元素属性(例如宽度,高度等)时,有时它不起作用.在这种情况下,您可能想尝试这样做:
$scope.$watch('$viewContentLoaded',
function() {
$timeout(function() {
//do something
},0);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
389059 次 |
| 最近记录: |