Updating the title with respect to the current route in AngularJS 1

Is it possible to dynamically change the title displayed in a header based on the current route provided by the router, even when outside of the controller scope? For example, I have a mainMenu controller that is loaded when a specific route is called. The header, which is included as a partial outside of the view, should reflect this current route. Below is the code structure for reference:

index.html

<div ng-include="'partials/header.html'"></div>
<div ng-view></div>

/partials/header.html

<header ng-controller="HeaderCtrl">
      <h1>{{ currentTitle }}</h1>
</header>

/partials/main-menu.html

<div ng-controller="MainMenuCtrl">

</div>

Router

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

TaskApp.config(['$routeProvider',
  function($routeProvider){
  $routeProvider.
      when('/main-menu', {
        templateUrl: "partials/main-menu.html",
        controller: "MainMenuCtrl"
      }).
      otherwise({
        redirectTo: "/"
      });
  }]);

Controllers:

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

taskAppControllers.controller('TaskAppCtrl',[function(){}]);
taskAppControllers.controller('DesktopCtrl',[function(){}]);

taskAppControllers.controller('MainMenuCtrl', ['$scope','$http',
 function($scope, $http){
  $http.get('data/main-menu.json?' + Math.random()).success(function(data){
    $scope.mainMenuOptions = data;
  });
  $scope.currentTitle = "Main menu"
}]);

taskAppControllers.controller('HeaderCtrl', ['$scope',
 function($scope){
   //
}]);

Answer №1

If you want to enhance the functionality of your routes, consider adding a new property called title to each route option.

when('/main-menu', {
    templateUrl: "partials/main-menu.html",
    controller: "MainMenuCtrl",
    title: 'Main Page'
}).

To utilize this new property, include the $routeChangeSuccess event within the HeaderCtrl. This event is triggered when route changes are successfully completed. Access the current route object, retrieve its title value, and assign it to the currentTitle scope variable.

$scope.$on('$routeChangeSuccess', function(event, current) {
    $scope.currentTitle = current.title;
});

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

Building forms within an AngularJS directive

I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field. The distinguishing factor between the two child forms ...

Understanding the process of verifying signatures with Cloud KMS

I've been struggling to confirm the validity of a signature generated using Google's cloud KMS, as I'm consistently receiving invalid responses. Here's my approach to testing it: const versionName = client.cryptoKeyVersionPath( p ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...

Show two spans, each underneath the other

I am looking to showcase two span elements, one below the other. Take a look at my HTML code snippet <img class="profile-photo margin-0" data-ng-if="!question.isOpen" ng-src="{{question.profilePicId ? que ...

Is there a versatile Node.js HTTP request module that is compatible with both server-side and browser-side development, particularly when packaged with Webpack?

Currently, I am searching for a request module that can operate seamlessly in both the Node.js server and the client when compiled with Webpack. The requirements are quite straightforward. I simply need to execute some basic HTTP Ajax requests such as get ...

Retrieve characteristics from removed or replicated entities and allocate them to different entities

Looking for a bit of assistance with an array transformation: [ {Code:13938, Country:699, Name:"Crocs", codeProduct:1} {Code:13952, Country:699, Name:"Polo Club", codeProduct:14} {Code:13952, Country:699, Name:"Polo Club", codeProduct:1} {Code ...

It is not possible to include external JavaScript in a Vue.js web page

Trying to integrate a Google Translate widget onto my webpage has been a bit challenging. Initially, when I added it to a normal webpage, it worked smoothly using the following code: <div class="google_translate" id="google_translate_element"></d ...

Is there a way to showcase an epub format book using only HTML5, CSS, and jQuery?

Can ePub format books be displayed in a web browser using only HTML5, CSS, and jQuery? I would appreciate any suggestions on how to accomplish this. Additionally, it needs to be responsive so that it can work on iPad. While I am aware of this requirement, ...

How can I arrange the ng-class based on the clicked item's order?

http://plnkr.co/edit/pUtuZy?p=preview In this scenario, there are three different border classes available: .border1 { border: 1px solid #66FFFF; } .border2 { border: 1px solid #33CCFF; } .border3 { border: 1px solid #0099FF; } The goal is to as ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...

Seeking guidance on capturing the correct error message when using JSON stringify?

Imagine I have an object structured as follows var obj = { "name": "arun" age } After attempting JSON.stringify(obj), it results in an error due to the improper structure of the obj. I am interested in capturing this error displayed in the console and pr ...

Navigate to a specific URL path and send properties as arguments in the function for handling events

I am working on a vuetify autocomplete search feature. When a user selects an item, I need to navigate to a specific route and pass some props along. However, my attempts to change the current route without passing props have resulted in errors. Here is w ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

Running AngularJS within an Angular 8 application using ngUpgrade is not supported

Struggling to get my Hybrid Angular application up and running using ngUpgrade according to the documentation. The issue is that no matter what tweaks I make, AngularJS just won't cooperate. When I combine Angular and AngularJS, both applications wor ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Things, their examples and the impact of setTimeOut

I'm currently delving into object oriented programming in JavaScript. function doStock() { //my class var that = this; var nAntiFreeze = null; // timeout ID var getContent = function(oInPageContainer) { GM_log('Antifreeze, before clea ...

Having trouble with Gatsby: page not showing when passing parameters in URL [Need assistance]?

Having trouble extracting the URL parameter (/mypage/?title=my-title) from the URL and displaying it on the page. I've attempted client-only routes in Gatsby. import path from "path" exports.onCreatePage = ({ page, actions }) => { const ...

What are the steps to implement an Express Error handling middleware in my specific scenario?

I have implemented a router middleware to validate requests and a global Error handler middleware in the server.js file to handle all errors. However, I am encountering an issue within the router while trying to implement this logic. The problem is highli ...

Encountering an issue with WebRTC where the 'addIceCandidate' function on RTCPeerConnection is failing, resulting in an error displayed on the console. However, despite this error

I am facing an issue with connecting two peers using webRTC. While I can successfully display both local and remote videos, as soon as the remote video appears, the candidate object turns null and an error message is logged on the console. TypeError: Fail ...