Victor Le
Victor Le

Reputation: 1788

Angularjs Ui Router Params in EJS

?

This might be an odd question but i'd like to know if its possible to achieve. I'm passing in a value to a param from the html side. Grabbing that value using $stateParams. I console that out and of course I get the value. Is there a way I can pass in that value to the end of the ejs like how I did below? Note that every time I use this method I get an Injection error from angular. When I remove the additional $stateParams.id that I was trying to add to the templateUrl string, the error goes away. So it seems like I can't pass it in there obviously. Any work around?

Angular part

.state('home',{
  url: '/home/:id',
  controller: function($stateParams){
    console.log($stateParams.id);
  },
  templateUrl: '/myRoute/'+$stateParams.id,
});

HTML

<a ui-sref="home({id: 2345})">Click me</a>

Assuming that my Backend route is set up like this

router.get('/myRoute/:id', function(req, res, next) {
  console.log(req.params.id);  //I would like to get my params here pass down from the view
});

I have a situation where I need that angular state to have a view as a ejs file instead of a regular html because of weird reasons...I was able to pull up the ejs onto the screen through the router but no luck getting the params that I needed. It comes up undefined on the server side when I try to console it out.

Upvotes: 2

Views: 194

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Error happening because $stateParam dependency isn't available there(you haven't injected anywhere expect controller function, which is restricted to controller function).

Best way to get access to $stateParams would be, do add function to return templateUrl & have 1st parameter params which will give you access to $stateParams

.state('home',{
    url: '/home/:id',
    controller: function($stateParams){
       console.log($stateParams.id);
    },
    templateUrl: function(params){
       return '/myRoute/'+params.id;
    }
});

Upvotes: 1

Related Questions