[英]AngularJS document.ready doesn't work when using ng-view
在我的应用程序中的多个路线之间导航时,我在angularJS中遇到了document.ready的问题。 它只适用于我使用ctrl + f5(页面重新加载); 它似乎在页面之间导航不会改变文档的状态以备就绪。
调节器
angular.element(document).ready(function() {
window.scrollTo(0,90);
});
主要的html文件
<!DOCTYPE html >
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title></title>
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
应用文件
var mainModule = angular.module('myApp', ['ui.bootstrap.dialog']);
function viewServiceConfig($routeProvider) {
$routeProvider.
when('/', {
controller: SomeController,
templateUrl: 'somehtml.html'
}).
when('/someroute', {
controller: SomeRouteController,
templateUrl: 'someroutehtml.html'
}).
otherwise({
redirectTo: '/'
});
}
mainModule.config(viewServiceConfig);
您可以在路径中定义的控制器中侦听,即$viewContentLoaded
事件的 SomeController
和SomeRouteController
。 每次重新加载ngView内容时都会发出$viewContentLoaded
并且应该在angularjs中路由时提供与document.ready
类似的功能:
function SomeController($scope) {
$scope.$on('$viewContentLoaded', function() {window.scrollTo(0,90);});
}
加载index.html
时, document.ready
也只会被触发一次。 加载路径配置中定义的部分模板时,不会触发它。
扩展@davekr的答案,我发现我需要添加$ timeout以确保摘要已完成并且html元素可用于查询:
function SomeController($scope) {
$scope.$on('$viewContentLoaded', function() {
$timeout(function(){
//Do your stuff
});
});
}
我尝试了很多其他事件,这是唯一可行的方法。
我能够通过Dave的答案和使用routeChangeSuccess来应用滚动事件
function SomeController($scope) {
$scope.$on('$routeChangeSuccess', function() {window.scrollTo(0,90);});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.