Dinesh Rawat
Dinesh Rawat

Reputation: 1019

how to make url with dynamic username in angular 1?

I am new to angularJs (version 1), I am trying to write a route for my application using ui-router.

My application opens on the browser using the below link:

http://localhost:8000/ that is converted to http://localhost:8000/#/

There are some other links like http://localhost:8000/#/contactus and http://localhost:8000/#/posts etc.

Problem is:

http://localhost:8000/#/

fetches a user's data from remote. currently, I have hardcoded the username to get the details.

I want to make it dynamic by passing the username in the url like as follows:

http://localhost:8000/{myName}/

Example:

http://localhost:8000/jack

Please suggest, how should I write the route (using ui-router state). I don't want to change the urls.

Should I create .htaccess file to rewrite the url or is it possible in angular somehow?

$stateProvider
        .state('main', {
            views: {
                "myWidget": {
                    template: "<div ui-view='my_nested_view' id='my_nested_view'> <div/>",
                    controller: myWidgetCtrl
                }
            }
        })
        .state('main.contactus', {
            url: '/contactus',
            views: {
                "my_nested_view@main" : {
                    template: 'contactus.html',
                    controllerAs: 'contactusCtrl',
                    controller: contactusController
                }
            }
        })
        .state('main.posts', {
            url: '/posts',
            views: {
                "my_nested_view@main" : {
                    template: postsTemplate,
                    controllerAs: 'postsCtrl',
                    controller: postsController
                }
            }
        });

I want to allow the user to pass his username in the url.

For example

localhost:8000/ it opens the home page that is correct.

localhost:8000/stackg91 currently give not found error. I want to allow the user to pass username in the url, Instead of giving error it should open the home page.

base url: http://localhost:8082/#/

want to pass http://localhost:8082/dinesh/#/

Upvotes: 0

Views: 649

Answers (1)

Pathik Patel
Pathik Patel

Reputation: 185

You can use url parameter for passing username to fetch user details

Your state definition would be::

$stateProvider
    .state('UserDetails', {
        url: "/:userId",  //
        templateUrl: 'UserDetails.html',
        controller: 'UserDetailsCtrl'
        }
    })

And this would be the controller:

.controller('UserDetailsCtrl', function($scope, $state, $stateParams) {
    //..
    var userId = $stateParams.foo; //getting userId


})

Which means, that the params in url are expected as

url: '/:userId',

For passing arguments into the controller:

<a ui-sref="UserDetails({userId:'jack'})"></a>

For more reference on ui-routing, you can use this link

Upvotes: -1

Related Questions