AngularJS document.ready 在使用 ng-view 时不起作用 [英] AngularJS document.ready doesn't work when using ng-view

查看:29
本文介绍了AngularJS document.ready 在使用 ng-view 时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中的多个路由之间导航时,angularJS 中的 document.ready 出现问题.它仅在我使用 ctrl+f5(页面重新加载)时有效;似乎在页面之间导航不会将文档状态更改为就绪.

控制器

 angular.element(document).ready(function() {window.scrollTo(0,90);});

主 html 文件

<html ng-app="myApp"><头><meta http-equiv="content-type" content="text/html;charset=utf-8"/><title></title><身体><div class="容器"><div ng-view></div>

</html>

应用文件

var mainModule = angular.module('myApp', ['ui.bootstrap.dialog']);功能 viewServiceConfig($routeProvider) {$routeProvider.什么时候('/', {控制器:SomeController,templateUrl: 'somehtml.html'}).当('/某条路线',{控制器:SomeRouteController,templateUrl: 'someroutehtml.html'}).除此以外({重定向到:'/'});}mainModule.config(viewServiceConfig);

解决方案

你可以监听你在路由中定义的控制器,即 SomeControllerSomeRouteController for $viewContentLoaded 事件.每次重新加载 ngView 内容时都会发出 $viewContentLoaded 并且在 angularjs 中路由时应该提供与 document.ready 类似的功能:

function SomeController($scope) {$scope.$on('$viewContentLoaded', function() {window.scrollTo(0,90);});}

document.ready 也仅在您加载 index.html 时触发一次.加载路由配置中定义的部分模板时不会触发.

I have a problem with document.ready in angularJS when navigating between several routes in my app. It only works when I use ctrl+f5 (page reload); it seems navigating between pages does not change state of the document to ready.

Controller

  angular.element(document).ready(function() {
    window.scrollTo(0,90);
});

Main html file

<!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>

app file

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);

解决方案

You can listen in your controllers defined in routes i.e. SomeController and SomeRouteController for $viewContentLoaded event. $viewContentLoaded is emitted every time the ngView content is reloaded and should provide similar functionality as the document.ready when routing in angularjs:

function SomeController($scope) {
   $scope.$on('$viewContentLoaded', function() {window.scrollTo(0,90);});
}

The document.ready is also triggered only once when you load your index.html. It is not triggered when the partial templates defined in your route configuration are loaded.

这篇关于AngularJS document.ready 在使用 ng-view 时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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