AngularJS document.ready doesn't work when using ng-view

前端 未结 3 1915
粉色の甜心
粉色の甜心 2020-12-13 20:14

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 betwe

相关标签:
3条回答
  • 2020-12-13 20:29

    Expanding on @davekr's answer, I found I need to add a $timeout to ensure the digest had complete and the html elements were available to query:

    function SomeController($scope) {
        $scope.$on('$viewContentLoaded', function() {
            $timeout(function(){
                //Do your stuff
            });
        });
    }
    

    I tried many other events and this was the only way that worked reliably.

    0 讨论(0)
  • 2020-12-13 20:35

    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.

    0 讨论(0)
  • 2020-12-13 20:49

    I was able to apply the scroll event through Dave's answer and by using routeChangeSuccess

    function SomeController($scope) {
        $scope.$on('$routeChangeSuccess', function() {window.scrollTo(0,90);});
    }
    
    0 讨论(0)
提交回复
热议问题