URL Labeler StateProvider: A unique StateProvider that adds a distinctive label to the

I need help figuring out how to add a user-friendly URL at the end of the current URL using $stateProvider.

As an example, on StackOverflow's question pages, the URL format is stackoverflow.com/questions/(question_id)/(question title). I want to replicate this behavior in my project by simply adding the question_id and then appending a relevant phrase. Any suggestions?

$stateProvider
  .state('question', {
    url: '/question/:qid',
    templateUrl: 'q.htm',
    controller:'bla'
    resolve: {
        title: function($http, $stateParams){
            return $http.get('title/'+$stateParams.qid);
        }
    }
  });

After that, I'm looking for a way to attach the retrieved title to the existing URL structure.

Answer №1

After brainstorming, I devised a solution: ( click 'Locations' and the table row on this demo )

I included the id and name parameters within $stateProvider.state

url: "location/:lid/:name",

If 'lid' was left unspecified, 'name' would also be missing, resulting in 'location//' displayed in the URL. In such cases, setting lid = 'all' and name = '' informs the controller to display all locations instead of a specific one.

lid: function($stateParams){
    $stateParams.lid = $stateParams.lid || 'all';
    return $stateParams.lid;
},

Next, I made lid a dependency and injected it into getName. Utilizing $q as an alternative to $http demonstrated that promises work effectively here for the subsequent dependency with a random timeout duration.

getName: ['$q','$timeout','lid', function($q, $timeout, lid){
    var deferred = $q.defer();

    $timeout(function() {
        var names = ['Cool Place', 'Awesome place', 'boring place', 'I want to be here', 'Random Venue'];
        deferred.resolve(names[ parseInt(lid) % 4 ]);
    }, Math.round(Math.random()*200));

return deferred.promise;
}],

Then, I injected getName and lid into name:

name : ['lid', '$state','$stateParams','getName', function (lid, $state, $stateParams,getName) {
    if($stateParams.lid.length < 1 || $stateParams.lid == 'all'){
        $stateParams.name = '';
        return '';
    }
    if($stateParams.name.length > 0){
        return $stateParams.name;
    }

    getName = getName.replace(/\s/g,'-');

    $state.transitionTo('dashboard.location', {lid:lid, name:getName}, {
        reload:true,
        inherit:false,
        notify:true
        })
}]

If the name is absent from the parameters, transitioning with a 'reload' property set to true is necessary.

A comprehensive demo can be accessed by ( clicking 'Locations' and the table row on this demo )

To summarize everything:

.state('dashboard.location', {
            templateUrl : "apps/location/template/location_template.htm",
            controller: 'LocationCtrl',
            url: "location/:lid/:name",
            resolve: {
                ctrl: function($ocLazyLoad){
                    return $ocLazyLoad.load({
                        name: "dashboard.location",
                        files: ['apps/location/location_controller.js', 'apps/location/style/location.css']
                    });
                },
                lid: function($stateParams){
                    $stateParams.lid = $stateParams.lid || 'all';

                    return $stateParams.lid;
                },
                getName: ['$q','$timeout','lid', function($q, $timeout, lid){
                    var deferred = $q.defer();
                    $timeout(function() {
                        var names = ['Cool Place', 'Awesome place', 'boring place', 'I want to be here', 'Random Venue'];
                        deferred.resolve(names[ parseInt(lid) % 4 ]);
                    }, Math.round(Math.random()*200));
                    return deferred.promise;
                }],
                name : ['lid', '$state','$stateParams','getName', function (lid, $state, $stateParams,getName) {

                    if($stateParams.lid.length < 1 || $stateParams.lid == 'all'){ // show all or not set Location ID
                        $stateParams.name = '';
                        return '';
                    }
                    if($stateParams.name.length > 0){ // if the name is already specified, it's ok. settle
                        return $stateParams.name;
                    }

                    getName = getName.replace(/\s/g,'-');

                    $state.transitionTo('dashboard.location', {lid:lid, name:getName}, {
                        reload:true,
                        inherit:false,
                        notify:true
                    })
                }]
            }
        })

This detailed guide may assist others in similar scenarios.

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

JavaScript has received an event on Server XHR

Situation: There is a scenario where the target API is external and cannot be altered. A JS client initiates sending data to the API upon clicking a button. The code snippet resembles something like this: $.ajax({ type: "POST", url: &quo ...

Storing data from a massive JSON array into a separate array using a specific condition in JavaScript

Dealing with a large JSON array can be challenging. In this case, I am looking to extract specific objects from the array based on a condition - each object should have "dbstatus":-3. data = [{"id":"122","dbstatus":-3},{"id":"123","dbstatus":"-6"},{"id" ...

What is the best way to deactivate a hyperlink on a widget sourced from a different website?

Is there a way to remove the link from the widget I embedded on my website without access to other editing tools besides the HTML code provided? For instance, we have a Trustpilot widget at the bottom of our page that directs users to Trustpilot's web ...

Leveraging $sceDelegateProvider for allowing Youtube in Typescript

I'm currently facing an issue with my app where I am trying to enable users to input Youtube URLs for videos to be displayed on the site. However, before implementing this feature, I need to whitelist Youtube. How can I adjust my typescript file (app. ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

What is the best way to retrieve a response from a modal dialog using jQuery?

Is there a way to utilize an add-in such as simple-modal or the dialog add-in in the UI kit to achieve AJAX interaction with the server? I am looking for a solution that allows the modal to communicate with the server and return the result back to the ca ...

Error encountered while attempting to save user to mongoose due to bcrypt issue

I am currently dedicated to expanding my knowledge in node and react through a tutorial. If you want to check out the repository, here is the link: While making a post request to /api/users/register, I encountered an error that seems to stem from an unde ...

Move the items downwards to occupy any empty space vertically

Just a quick overview of the code I'm working with (I am using Material UI in React). This container is meant to hold chat messages exclusively. const ChatContainer = ({ chatMessages }) => { const classes = useStyles(); return ( <Paper ...

Ensure that autocorrect is set to suggest the nearest possible quantity form in WordPress

I'm currently in the process of creating a webshop using WooCommerce. Our quantity system is a bit unique, as we are using WooCommerce advanced quantity, which means that quantities increase by 0.72 increments (e.g. 0.72, 1.44, 2.16 etc). The +/- butt ...

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...

The addition of input fields on keyup creates problems in the initial field of each row

I am currently working with a table and attempting to calculate the sums as follows: td(1) + td(2) + td(3) = td(4), td(5) + td(6) + td(7) = td(8), td(9) + td(10) + td(11) = td(12). This is the code I have implemented: $(document).ready(function () { ...

res.cookie function is unable to set cookies in the Chrome web browser

During development, I have a basic login page running locally on my machine (http://127.0.0.1:5500/index.html) and a simple express server running at http://localhost:3003 Despite seeing the server sending my access_token in response headers, Chrome brows ...

How can I include inline CSS directly within a string instead of using an object?

Is there a way to write inline CSS in a string format instead of an object format? I attempted the following, but it did not work as expected: <div style={"color:red;font-weight:bold"}> Hello there </div> What is my reason for want ...

The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice ...

Issue with Refreshing onRowAdd in React Material Table

I am currently using Material Table to display my table data. However, when I use the onRowAdd function to add a new row, the page does not refresh properly. Instead, it reloads and gets stuck, requiring me to manually refresh again. newData => ...

Exploring the ins and outs of webpage loading speed

I am working on writing JavaScript code that includes a button to open a webpage of my choice. I now want to understand how to detect when the page I called is finished loading. Any suggestions or ideas on this topic? I apologize if my explanation was no ...

What is the most efficient way to access a cell within an HTML table using jQuery or the Document Object Model (

I have an unchangeable HTML table styled with CSS. My goal is to extract the value from the first column for filtering purposes. I've been struggling to locate a suitable jQuery or DOM function to accomplish this task. Unable to find a way to access ...

What is the process of uploading a video and showcasing it on an HTML page?

I have successfully uploaded images and displayed them on an HTML page. Now, I am looking to do the same for videos. Here is my current code: $('#addPhotosBtn').click(function() { $(this).parents().find('#addPhotosInput').click(); }) ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...