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

Instructions on how to delete a specific tag from a table using its ID

I have a complex HTML table generated by a PHP loop with multiple rows. My goal is to eliminate all the a tags within the td tag where the ID of the td tag is equal to 1 or another specified value. <table> <tr> <td>ID: 1</ ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

Adding JQuery to a running webpage using the DOM and Opera browser add-ons

I'm currently working on an Opera Extension and I have a question. Is there a way to use the includes folder in order to directly inject jQuery into the live HTML of a webpage? For example, can I change the background color of the DOM to black? If ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

"I'm looking for a solution on integrating Osano CookieConsent into my Next.js application. Can

I'm facing a bit of a challenge with incorporating the Osano Cookie Consent JavaScript plugin into my nextjs app. I've been attempting to set up the cc object by initializing it in the useEffect of my root landing page: const CC = require( " ...

What could be the reason for AngularJS directives (such as attributes) appearing as "invalid" in WebStorm 8?

Just recently, I downloaded and installed WebStorm 8 onto my computer. I have been working on some AngularJS projects and have encountered a frustrating issue. The AngularJS plugin appears to be only partially functioning - when I type ng- in the code edit ...

What is the proper way to utilize the name, ref, and defaultValue parameters in a select-option element in React Meteor?

I recently developed a Meteor project using ReactJS. I have a Create/Edit page where I use the same input field for various form elements. Here is an example of code snippet that I currently have: <FormGroup> <ControlLabel>Province</Control ...

Validating HTML forms using Javascript without displaying innerHTML feedback

Hey, I'm just diving into web development and I'm struggling to figure out why my innerHTML content isn't displaying on the page. Can anyone offer some assistance? I'm trying to display error messages if certain fields are left empty, b ...

Having trouble with getStaticProps serialization error in Next.js?

I encountered an error in my Next.js application that reads as follows: Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only ret ...

An alternative to passing AngularJS expressions to PHP or Ajax

Within my PHP/HTML file, I have an AngularJS expression that looks like this: {{data.po_id}} This expression is included as <td>{{data.po_id}}</td> within a table row. I am trying to use this expression as a parameter for a PHP function in t ...

Is pl/pgsql block code supported by postgres-nodejs?

I am attempting to define a custom UUID variable that can be utilized across multiple queries within a transaction. Initially, I attempted using a JavaScript variable which ultimately defeated the purpose of declaring the variable on the server side. The ...

After ajax, trigger change event

Can anyone assist me in combining multiple functions within the same form using AJAX? The purpose of the form is to prenote a new "meeting" and it consists of an input for the date and a select dropdown for choosing the operator. FORM CODE: <div id=&qu ...

Utilize React Material UI to elegantly envelop your TableRows

Currently, I am faced with a challenge involving a table that utilizes Material UI and React-table. My goal is to wrap text within the TableRow element, but all my attempts have not been successful so far. Is there anyone who knows the best approach to a ...

`Using angular-ui-tree: Retrieving the html element of the most recent node that was added`

Perhaps this question may seem trivial, but despite my efforts to research on stackoverflow and angular-ui-tree documentation, I have not been able to find a solution. I am in need of obtaining the HTML element of the most recently added node. To be spec ...

Increase the progress bar at regular intervals of x seconds

I am looking for a jQuery UI progress bar that will increase by x amount every x seconds. Once it reaches 100%, I need it to trigger a function to retrieve some content. Essentially, I need a timer-like feature. EDIT: Note that I do not require any code ...

Extract information from a database table for presentation as simple text

I am looking to extract information from each row and display it as plain text on the same page within a paragraph. Here is an example table for reference: <table> <thead> <tr> <th class="a header">A</th ...

Display all elements with a blank attribute using jQuery

I'm currently dealing with a list containing multiple hidden list items: <ul> <li rel=""> </li> ... </ul> My goal is to display only those list items that have an empty string as the value of the attribute rel. D ...

"Step-by-step guide on assigning a class to a Component that has been

When attempting to pass a component as a prop of another component, it functions correctly. However, when I try to pass a Component and manage its CSS classes within the children, I find myself stuck. I am envisioning something like this: import Navbar fr ...

Error: Unable to access 'target' property as it is undefined in React JS

I am currently working on capturing the value of a select tag that triggered an event, but I am encountering an issue when changing the tag. An error message pops up saying TypeError: Cannot read property 'target' of undefined. It seems to indica ...

Unexpected updates occurring in custom Google Sheet functions

Currently, I am utilizing a personalized function to retrieve price data for EVE Online. However, I am encountering an issue where the function is updating every 10-20 minutes, leading to a depletion of my daily URL Fetches quota. The primary function can ...