The AngularJS app.run function fails to initialize

I am encountering a problem with app.run(). On the main page, app.run() is functioning properly. However, when I click on the Events menu button and navigate to the events.html page, app.run() does not work initially. It only starts working after I reload the page. Both the main.html and events.html pages are within the ngView, and the menu is also within the ngView.
controller.js

afroEarthApp.config(['$routeProvider', function($routeProvider){
    $routeProvider
      .when('/',{
        templateUrl:'template/home.html',
        controller:'afroEarthMainCtrl'
      })
      .when('/events',{
        templateUrl:'template/events.html',
        controller:'eventsCtrl'
      })
      .when('/sites/:niche', {
        templateUrl:'template/single.html',
        controller:'SingleCtrl'
      })
      .otherwise({
        redirectTo: '/'
      })
}]);
afroEarthApp.controller('afroEarthMainCtrl',['$scope','$http','$location','$cookies', '$rootScope', '$route', function($scope, $http, $location, $cookies, $rootScope, $route) {
...some code...
}]);

afroEarthApp.controller('eventsCtrl',['$scope','$http','$location','$cookies', '$rootScope', '$route', function($scope, $http, $location, $cookies, $rootScope, $route) {
...some code...
}]);

afroEarthApp.run(['$log', '$rootScope', '$route', function ($log, $rootScope, $route) {
    $rootScope.$on('$viewContentLoaded', function ($rootScope, $route) {
...some code...
})
}]);

home.html

        <ul class="nav navbar-nav navbar-right">
            <li><a class="page-scroll" href="#websites">Lifestyle sites</a></li>
            <li><a class="page-scroll" href="stories">Success Stories</a></li>
            <li><a href="#/events" data-target="#events" target="_self">Events</a></li>
            <li><a class="page-scroll" ng-href="http://{{singleNiche.url}}.afroearth.com/login/">Login</a></li>
            <li class="other-countries">
                <a href="#">
                    {{singleNiche.country}}<img src="{{singleNiche.countryFlag}}"><i class="icon-caret-down"></i>
                </a>
                <ul>
                    <li ng-repeat="country in singleNiche.countries"><a ng-click="setCountry(country.url)" >{{country.name}}</a></li>
                </ul>
            </li>
        </ul>

I would appreciate any help with this issue.

Answer №1

Include the following code snippet in your app.run section:

$rootScope.$on('$locationChangeStart', function (event, nextLocation, currentLocation) {
// Add your custom code here
});

The above function will be triggered every time there is a change in the URL.

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

Transform post-back into PHP using JSON for Ajax posting

Currently, I am facing a challenge in integrating a Codeigniter application into Wordpress using a plugin. The trouble arises when the control encounters an issue while confirming the data for a new appointment. VIEW <div id="wizard-frame- ...

Optimizing Google e2e testing using Protractor

Improving login efficiency is necessary to enhance the speed of executing e2e tests. At present, after every test, the Chrome browser shuts down, requiring a new login session for each subsequent test. What changes can be made to address this issue? Any ...

In search of a regular expression that restricts special characters from occurring at the beginning of a string, allowing only apostrophes, spaces, and hyphens elsewhere

In my quest for answers to this regex query, I have scoured the depths of the internet. While I am close to finding a solution, it seems I may be missing one or two additional groups to prevent special characters from appearing at the beginning and end of ...

Why isn't my Angular directive able to access the parent controller's scope within its isolated scope?

I have meticulously followed the Angular documentation to implement a directive with an isolated scope that contains a few variables from the parent Controller's scope object. app.controller('MainCtrl', function($scope) { $scope.name = ...

Mobile browser experiences video freezing when src is set through useState, yet it starts playing when triggered by a button click or when the video is set to M

Hey awesome folks at the StackOverflow Community, I'm currently encountering a perplexing issue with a video element in my web application. The video is supposed to play automatically on both desktop and mobile browsers. However, I've run into a ...

Click on a specific button within a DataTable row

I am working with a dataTable that fetches data from the database using Jquery. In each row, there are two buttons for accepting or rejecting something. My goal is to make the accept button disappear when rejecting and vice versa. public function displayT ...

Tips for verifying login credentials with MongoDB and Express: Leveraging db.collection().findOne() or .find() functions

I am encountering an issue with a POST request involving user credentials being sent from a Login page to the API Server. The code looks like this: loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { ...

Refreshing a DIV in Rails by reloading from model using a JavaScript function

Recently, I created a page displaying the number of Widgets a customer has. Below is the view written in Haml: #available = "Available widgets: #{@customer.widgets.unused.count()}" (The "unused" scope in the model displays available widgets). When a C ...

What is the best method to create Promise API synchronously?

When it comes to testing with NodeJS, I rely on selenium-webdriver. My goal is to streamline the selenium-webdriver API by making it synchronous, which will result in more concise tests. The method getTitle() is used to retrieve the title of the current p ...

The Vue CLI build is displaying a blank page when hosted on an Apache server

I encountered an issue with vue cli. Running npm run serve went smoothly, but when I tried dev mode using npm run build-dev, the build process finished with a blank page displayed. The error message received was "Uncaught SyntaxError: Unexpected token &ap ...

Implementing intricate inline styles in React for interactive features like hover and active states on components like buttons

I'm currently styling my buttons using the following CSS with Bootstrap. .btn-primary { background-color: #229ac8; background-image: linear-gradient(to bottom, #23a1d1, #1f90bb); background-repeat: repeat-x; border-color: #1f90bb #1f9 ...

Attempting to adjust numerical values to display with precise two decimal places using jQuery

Possible Redundancy: JavaScript: how to format a number with only two decimal places I'm getting confused while using variables and now I can't seem to get the calculation working correctly. Any ideas? $("#discount").change(function(){ ...

Using a uibCollapse within a nested directive element may not function as expected

Whenever I try to click on my custom directive, the elements that are supposed to expand remain collapsed. To ensure that the click event is actually triggered, I have specified a size in the css for the .btn class. // index.html <body ng-controller=" ...

What is the best way to change the size of a QR code

My current HTML code: <input id="text" type="text"/> <div id="qrcode"></div> Previous version of JAVASCRIPT code: var qrcode = new QRCode("qrcode"); $("#text").on("keyup", function () { qrcode.makeCode($(this).val()); }).keyup().focus ...

The partition.nodes(root) function in d3.js does not assign values to the x or dx properties of the nodes

I am currently experimenting with d3.js to create a unique icicle tree visualization using data sourced from a .json file. The challenge I'm facing lies in the fact that the x and dx attributes of the partition nodes are consistently being set to 0. M ...

Data is successfully being stored in an array in AngularJS, however, it is not appearing in the user interface

Having an issue with displaying updated data on my UI. I am successfully pushing data into the database and an array using Angular 2-way binding. The data is being pushed as confirmed by the console, but it's not showing up on the user interface. Con ...

require.js configuration encountered an error while trying to load jquery-ui for the fancytree plugin

I'm currently attempting to incorporate a jQuery control called fancytree into my project. This control has a dependency on jquery-ui. However, I am encountering an error indicating that jquery-ui has not been loaded from the specified path. In additi ...

Convert JavaScript back into an HTML attribute

Is there a way to include a JavaScript code in an HTML attribute like shown below? <div class="xx" animation="yy" animate-duration="<script>Code goes here<script>" ...> </div> I'm struggling to figure it out, is there a solut ...

Creating customizable form fields based on user input in Laravel - here's how!

I am feeling a bit lost when trying to generate dynamic fields based on user input. For example, this field is where the user can enter how many fields they want to create: {!! Form::open(array('url' => 'home')) !!} <div clas ...

Tips for identifying a scroll down gesture on a touch device with jQuery

I have a method for infinite scroll that is triggered like this: $(window).on('scroll resize load', function() { // execute the infinite scroll method }); It is triggered by these events: scroll resize load However, it does not seem to ...