Utilize $stateParams to dynamically generate a title

When I click a link to our 'count' page, I can pass a router parameter with the following code:

$state.go('count', {targetName: object.name})

The router is set up to recognize this parameter in the URL:

url: '/count/:targetName',

We are using the data: option in UI-Router along with $state to dynamically adjust page titles:

<title ng-bind="'Application Name : ' + $state.current.data.pageTitle"></title>

I want the pageTitle to include the :targetName as well. I attempted to achieve this by setting a function in the data: property of the router like so:

data: {
    pageTitle: function () {
        getTargetName.$inject('$stateParams');
        function getTargetName ($stateParams) {
            return $stateParams.targetName;
        }
    }
}

However, this approach prevents the page from resolving correctly.

Any suggestions or advice?

Answer №1

Visit the live Plunker demo

Explore these different states and their dynamic titles:

// Example of a state with a static pageTitle STRING
.state('home', {
    ...
    data: {
       pageTitle: "Just a home page"
    },
})
// Parent state with a URL parameter 'someParam' and a dynamic pageTitle as a function
.state('parent', {
    ...
    url: "/parent?someParam",
    data: {
        pageTitle: function ($stateParams) {
          return `Title with parameter ${$stateParams.someParam}`;
        }
    }
})
// Child state that changes the title
.state('parent.child', { 
    ...
    data: {
        pageTitle: "Just a child title",
    }
})

To display the title in your HTML, use this line of code:

<title>The title is: {{ getTitle() }}</title>

To make it work, we can add a simple evaluation to the $rootScope, or ideally, create a dedicated service for this purpose.

.run(['$rootScope', '$state', '$stateParams',
  function ($rootScope, $state, $stateParams) {

    $rootScope.getTitle = function(){
      var state = $state.current;
      var params = $stateParams;

      if (state.data
      && state.data.pageTitle) {

        if(typeof (state.data.pageTitle) === "function" ){
          return state.data.pageTitle(params);
        }
        return state.data.pageTitle
      }
      return "No title for this state"
    }
}])

Each link will now have its own unique title based on the state:

<a href="#/home">
<a ui-sref="parent({someParam: 1})">
<a ui-sref="parent({someParam: 'someValue'})">
<a ui-sref="parent.child">

See this implementation in action here

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

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

Running an Express middleware function

While watching a tutorial on the Express framework, I came across some interesting code used by the instructor for handling requests. Here is how the route is set up: router.route('/').post(authController.restrictTo('admin', 'l ...

Use a filter to narrow down results based on a column containing comma-separated values, as well as another specified

I am encountering an issue when attempting to apply filters on multiple columns within an object. The filters need to be applied based on the selection made in two drop-downs: one is directly linked to the ID, while the other holds the name but needs to be ...

Looking for a JavaScript snippet to insert the word "Search" into an empty DIV element with the specified id attribute

I am trying to insert the word "Search" into an empty input field with the id "ReportQuery" using JavaScript. Unfortunately, I do not have access to the HTML code directly. How can I achieve this task through coding? Below is the snippet of code that nee ...

Using a table row as a counter in HTML

I am looking for a way to automatically assign IDs to table rows using XSLT in a systematic manner. The idea is to have the ID consist of a string followed by a counter, like this: <table> <tr id="Row1"> # it can be only a number => id=" ...

Create a unique Bitcoin address using a derivation scheme

Starting with a derivation scheme that begins with tpub... for the testnet, I am looking to generate bitcoin addresses from this scheme. I also need a method that will work for the mainnet. Is there a library available that can assist me with this task? ...

Javascript Solution for Testing Palindromes in a Linked List

I recently researched the solution for a palindrome problem using Javascript. There is one particular line of code that I am struggling to comprehend, and I'm hoping someone can shed some light on it for me. Here is the code snippet in question: thi ...

My attempt at deploying my personal React App project on Vercel was unsuccessful

// encountering error during deployment on Vercel npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @testing-library/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99b8c888a9da9d8da ...

Before beginning my selenium scripts, I need to figure out how to set an item using Ruby in the browser's localStorage

Before running my selenium scripts, I am attempting to store an item in the browser's localStorage. I attempted to clear the local storage using this command: driver.get('javascript:localStorage.clear();') This successfully cleared the lo ...

React - Incorrect components experiencing style changes due to setTimeout

Check out the code snippet here: https://jsfiddle.net/69z2wepo/204131/ A main component displays two 'notifications' each with different disappearance timings. class Page extends React.Component { constructor(props) { super(props); t ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

notify a designated channel when ready for launch

I'm currently attempting to figure out how to send a message to a channel when the Discord bot is launched. I've experimented with this code: client.on('message', (message) => { client.on('ready', () => { channel = cli ...

In what scenarios is it more suitable to utilize style over the sx prop in Material-UI?

When it comes to MUI components, the style and sx prop serve similar purposes. While the sx prop provides some shorthand syntaxes and access to the theme object, they essentially function the same way. So, when should you opt for one over the other? ...

nested components in AngularJS

I am facing an issue with my two components in HTML where the inner component is not populating using the template specified in its templateUrl property. //first component angular.module('app').component('toolCtrl', { templateUrl: ...

Tips for adjusting the positioning of a div element in a responsive design

I am currently working on my website and facing a layout issue. In desktop mode, there is a sidebar, but in mobile view, the sidebar goes down under the content displayed on the left side. I would like the sidebar to appear at the top in mobile view, fol ...

Triggering jQuery Submit Form when Form is Modified

I need help with automatically submitting a form using jQuery when an input changes. The specific input I am working with is a date picker, and I want the form to be submitted as soon as a user makes a selection. <form id="select_date" name="select_da ...

The jquery selector fails to retrieve all elements

On the upcoming web page, I am attempting to use Jquery to select all <li> elements. Specifically, I want to target all the products contained within <ul class=search-result-gridview-items">. You can find the products here: I have made attempt ...

Implement a cron job in Node.js to automatically trigger an Express route on a weekly basis

I need to run tests on a certain page every week by creating a cron job that will access my express route at regular intervals. Currently, I have set up a cron job to run every 2 minutes as a test: //schedule job every 2 minutes schedule.scheduleJob("* /2 ...

Using Angular to link Google Places API responses to a form: a guide on merging two different length objects with a shared key

I'm struggling with a key concept here regarding displaying the results of a places autocomplete query. I want to replace the types[0] name with more familiar terms such as suburb or city instead of sublocality_level_1 or administrative_area_level_1 ...