AngularJS - Refreshing Controller when Route Changes

Scenario

 app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) {
     $scope.data = $routeParams;
 }]);

 app.config(['$routeProvider',
     function ($routeProvider) {
         $routeProvider.
             when('/:url', {
                 template: '<h2>Greetings Earthling</h2>'
             })
 }]);

Format

<body>
    <div ng-controller="headerController">
      Current URL: {{data.url}}
    </div>

    <div ng-view></div>

    <ul>
       <li>
          <a href="#/pageX">Page X</a>
       </li>
       <li>
         <a href="#/pageY">>Page Y</a>
     </li>
</body>

Dilemma

I am grappling with the issue of keeping the header section updated with the current url whenever the route is altered. It functions correctly upon initial loading but fails to update when a new route is selected.

While I acknowledge alternative solutions exist, my query centers on resolving this challenge within the confines of the existing setup. How can I ensure that a controller external to a view reflects the current route and automatically updates with each change in the route?

Answer №1

To improve performance, consider transforming $scope.data into a function so it can be reevaluated.

Another option is to utilize onRouteChangeSuccess event listener for monitoring URL changes.

Answer №2

After implementing your code and making some minor adjustments as indicated below, I have successfully tested it on my end using Firefox. The URL updates correctly to either Page A or Page B upon change.

Could it be that I misunderstood the question?

var app = angular.module('app', ['ngRoute']);

app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) {
     $scope.data = $routeParams;
}]);

app.config(['$routeProvider',
    function ($routeProvider) {
        $routeProvider.
        when('/:url', {
            template: '<h2>Hello World</h2>'
        })
}]);

<html ng-app="app">
<head>
    <script src="angular.min.js"></script>
    <script src="angular-route.js"></script>
    <script src="controller.js"></script>
</head>
<body>
    <div ng-controller="headerController">
      Current Url: {{data.url}}
    </div>

    <div ng-view></div>

    <ul>
       <li>
          <a href="#/pageA">Page A</a>
       </li>
       <li>
          <a href="#/pageB">Page B</a>
       </li>
</body>

Cheers

Nicolas

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

The controls for the Bootstrap carousel component do not have a clear appearance

Trying to implement a Bootstrap carousel component but facing an issue with the controls not appearing transparent like in the example provided in the Bootstrap documentation. Check out the code snippet: <div class="carousel slide" id="s ...

Issues with routing in Node.js using Express

This is my first attempt at programming. I am currently in the process of setting up routing in the following way: var indexRouter = require('./routes/index'); var loginRouter = require('./routes/login'); app.use('/', indexRo ...

Applying VueJS filters to refine object values

Is there a way to verify if the value of "startAt" is present in an object and return its corresponding ID? Here is the object in question: [{ "id": "1234567", "createTimestamp": "2020", "name": { "action": "", "allDay": false, "categor ...

The behavior of Angular 4 CSS and JS changes upon refreshing the page

Every time I try to load a page with this particular script: this.router.navigateByUrl('/report-result/'+report.id); It appears that not all the CSS and JS files are being loaded properly. The bootstrap popovers don't show up, and some ele ...

Error: Unable to access undefined properties (reading 'url')

I am currently working on creating a drag-and-drop card game and I have encountered an issue with the react-dnd library. When using data from the file, everything works fine, but if I have to fetch the data externally, it throws an error. This problem see ...

Animating elements on a webpage can be achieved by using both

Is there a way to create an animation that moves objects based on button clicks? For example, when the "Monday" button is pressed, the object with the correct color will move down. If any other button like "Tuesday" is clicked, the previous object will mov ...

Implement concrete actions on the right-click context menu

I am exploring the functionality of this right-click context menu. Visually, it appears as expected, but I am unsure how to implement actual actions when the menu items are clicked. Currently, it only displays a message like "Back menu item was clicked - t ...

EBUSY: Unable to access resource due to being busy or locked, unable to retrieve information from 'C:hiberfil.sys'

I am running into an issue while attempting to publish an npm package. The error message I keep receiving is causing me some trouble. Does anyone have any suggestions on how I can resolve this? Your help would be greatly appreciated! Thank you in advance ...

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...

What can be done to avoid causing other elements to blur when clicking a button?

Imagine a scenario where there is a textarea and a button present. If the button is clicked, typically the textarea will blur. However, in this case, I do not want that to happen. I am seeking advice on how to prevent the textarea from blurring u ...

Searching through an array for multiple values on the same key

I am currently working on dynamically generating a listview in jQuery. So far, I have been successful in creating the entire list dynamically. However, I now face the challenge of filtering, searching, or reducing my initial data: var recipes = [ { "name" ...

Empowering Components with React Hooks

I am currently in the process of transitioning from using class components to React hooks with the Context API. However, I am encountering an error and struggling to pinpoint the exact reason for it. Here are my Codes: // contexts/sample.jsx import React ...

Can a file be imported into Node.js without the need for packaging?

Is there a way to have an entire file evaluated in node? For example, let's say I want to evaluate the angular.js source file. An example of what the code could look like is as follows: jsdom = require("jsdom").jsdom; document = jsdom("<html>& ...

Executing multiple HTTPS requests within an Express route in a Node.js application

1 I need help with a route that looks like this: router.get('/test', async(req, res)=>{ }); In the past, I have been using the request module to make http calls. However, now I am trying to make multiple http calls and merge the responses ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

JavaScript not redirecting to HTML page as expected

I have developed a basic login page that makes an Ajax request to the backend. However, I am experiencing difficulties with redirecting the page upon successful login. The redirect function only seems to work 1 in 15 times, and I'm unsure of the reaso ...

Comparison Between Jquery and Emerging Javascript Frameworks and Libraries such as Angular, Ember, and React

As a ruby on rails developer, my recent foray into learning Angular and React has opened up new possibilities in the world of Javascript technologies. Despite reading comparison posts to gain insight into the reasons behind using different frameworks and l ...

What is the best way to center align my horizontal subnav?

I am currently working on a horizontal navbar with horizontal submenus. One issue I am facing is getting the elements in mysubnav to align centrally instead of being pushed to the left all the time. If you need a visual representation of what I mean, plea ...

Tips for Creating an Upward-Dropping Dropdown Menu in HTML/JavaScript When Space is Limited on the Page

Hello, I am currently seeking a solution to adjust my dropdown menu so that it appears above instead of below when the page doesn't have enough space to display it fully. My tools for this project include HTML, Javascript, CSS, and JQuery exclusively. ...