When utilizing ng-view in AngularJS, the document.ready function may not function as expected

Whenever I navigate between different routes in my AngularJS app, I encounter an issue with document.ready. It only seems to work when I do a hard refresh (ctrl+f5); navigating between pages does not trigger the ready state of the document.

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

Answer №1

To listen in your controllers defined in routes, such as SomeController and SomeRouteController, for the $viewContentLoaded event, use the following code snippet:

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

Keep in mind that the document.ready event is only triggered once when you load your index.html. It does not trigger when the partial templates defined in your route configuration are loaded.

Answer №2

Building on @davekr's response, I discovered that incorporating a $timeout was crucial to ensure the data digest had finalized and the HTML components were ready for querying:

function AnotherController($scope) {
    $scope.$on('$viewContentLoaded', function() {
        $timeout(function(){
            //Perform your actions here
        });
    });
}

I experimented with various other triggers, but this method proved to be the only consistently effective approach.

Answer №3

Thanks to Dave's insightful answer, I successfully implemented the scroll event using routeChangeSuccess

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the href of an image when the slide changes: Tips and tricks

Currently, I am utilizing the slick slider slideshow and facing an issue with updating the href of a logo image as the slides progress. Despite trying out two different scripts, none of them have proven to be effective. <main class="Site-content"> & ...

Choose and adjust the size of images with a specific aspect ratio using jQuery

As I work on my Tumblr blog, I am experimenting with using jQuery to target photo entries (imgs) based on specific aspect ratios and resizing them accordingly. To be more precise: If an image's width exceeds 250px, it should be resized so that the h ...

passport.initialize() function is currently inactive

For my project, I am utilizing node, express, mongoose, and passport. Initially, I successfully implemented a basic Log In functionality in my code within app.js. However, I decided to restructure my code to follow the MVC pattern, and after making the cha ...

Error encountered: Unknown token '<' and Loading chunk 16 unsuccessful

Having a react app created with create-react-app, I encounter errors whenever I deploy to netlify and there is a new build. Uncaught SyntaxError: Unexpected token '<' 16.0fcd6807.chunk.js:1 Immediately after this error, another one pops up: ...

Troubleshooting MySQL Database Insertion Errors caused by Dynamic Forms

<body> <?php $con = mysqli_connect('localhost','root','','cash'); $query = "SELECT DISTINCT category FROM cash"; $result = mysqli_query($con,$query); $dropDownList = &apo ...

How to optimize updating object properties with setState?

Is there a more efficient way to rewrite this code? For example, would using setState(ContentStore.getAll()) achieve the same outcome? I believe this approach appears overly cluttered and any method to simplify the code for readability would be greatly app ...

Getting the nested object property with pluck using Lodash

I have an array of objects containing character information: var characters = [ { 'name': 'barney', 'age': 36, 'salary':{'amount': 10} }, { 'name': 'fred', 'age': ...

Styling for jQuery (and javascript) code snippets

Is it just me, or does anyone else feel like they want to write javascript and jQuery in a different structure after making numerous mistakes with curly brackets and parentheses? I wish there was an IDE that could automatically collapse the code back into ...

The AngularJS API now includes the ability to store both the new and old values when saving

My goal is to enhance functionality by capturing both the old value and new value from the client side and saving them in separate tables using my API. For example, if a user changes their FirstName from 'aaa' to 'ccc' and their LastNa ...

Is there a way for me to extend an absolute div to the full width of its grandparent when it is within an absolute parent div?

Here is a structured example of my HTML and CSS: <div class="grandparent"> <div class="row">...</div> <div class="absolute-parent"> <div class="absolute-child">...</div> ...

How can I transmit information to the model without relying on query string parameters in Express?

Currently, I am working with two controllers - authController and onboardingController. The authController communicates with the onboardingController using the following line of code: res.redirect('/onboarding/info?profileId=' + profile.id + &ap ...

Capture microphone and audio in a SIP call with sip.js

Greetings Stack Overflow community! I am in need of assistance with a project involving sip.js and VoIP for making real phone calls. The Objective I aim to enable users to record audio from both parties during a call and save the data on a server (either ...

"Exploring the Power of Primefaces Dialog Framework: Unleashing the dialogReturn Event

I'm working with a primefaces p:datatable in Table.xhtml and have a p:commandbutton on the same page that triggers a dialog using the dialog framework. The dialog content is in Dialog.xhtml. Both the Table.xhtml and Dialog.xhtml are using a single bac ...

JavaScript: Receiving Varied Outputs from Comparable Functions

Here are two code snippets that contain an object and a function, both with identical content. They should theoretically return the same value. The only difference between the two is the presence of brackets and an 'else' statement in the 'f ...

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

Creating Stunning CSS Animations for a Slider Using SVG

Looking for help to create an SVG CSS animation for a slider using a mockup image. The animation will feature a balloon with a number value that zooms in and out from left to right or right to left. Currently stuck at the starting point and unsure how to ...

Image swaps with timer for button

I am working on a project where I have a page with 5 image buttons arranged horizontally. The objective is to have the images on each button change sequentially every 3 seconds in a continuous loop. Here is my code: $(document).ready(function (){ Beg ...

A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

Implementing the loading of a Struts 2 action with jquery in javascript

Looking to refresh a specific div using JavaScript with jQuery to target the div and a Struts action that loads the content. Can anyone offer advice on how to achieve this? The challenge lies in utilizing JavaScript and jQuery for this task. Best regards ...

Using jQuery to select the child element of the parent that came before

Recently, I've been experimenting with creating animations using CSS and jQuery. While it has been successful so far, I'm now looking to take it a step further. Specifically, I want information to appear on top of an image when the user clicks on ...