2

I got this URL into my system:

http://localhost/myapp/#/campaign/confirm/edit/:id

What are the best ways to get campaign, confirm and editinside my controller?

Alex M.
  • 635
  • 1
  • 6
  • 19
  • Will `campaign`, `confirm` and `edit` be parameters that can change? Such as, will `confirm` actually contain some value like `Y` or `N` that you're trying to capture? – Nicholas Hirras Mar 09 '15 at 19:24
  • No. `campaign`, `confirm` and `edit` doesn't change. `:id` do. – Alex M. Mar 09 '15 at 19:29
  • Are you using ngRoute? You shouldn't have to parse that at all. You will assign anything matching /campaign/confirm/edit/:id to a specific controller. At that point, the :id value is all you need to get. The tutorial discusses routing, a good place to start if you're new to it. https://docs.angularjs.org/tutorial/step_07 – Nicholas Hirras Mar 09 '15 at 19:39

1 Answers1

1

Looks like you've got this url formatted as an angular state (awesome!). In this case, you can access $stateParams in your controller.

https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service

That should have the information you need, assuming your state is something like this. This example makes all 4 parts into accessible variables, that's if you really do need ALL parts of that path. It's probably worth putting in some non-variable data in there, otherwise it might get a little difficult to separate this state from others that are formed in a similar way:

$stateProvider.state('myStateName', {
  url: '{campaign}/{confirm}/{edit}/{id}'
});

myModule.controller('fooCtrl', function($scope, $stateParams){
  console.log(
    $stateParams.campaign,
    $stateParams.confirm,
    $stateParams.edit,
    $stateParams.id);
});
HankScorpio
  • 3,612
  • 15
  • 27
  • They only tell me how to get the `:id`, not the path. – Alex M. Mar 09 '15 at 19:03
  • 1
    Get the full state name with: $state.current.name – HankScorpio Mar 09 '15 at 19:06
  • Although that's not what I asked for, it can solve my problem, @HankScorpio. This way I can create an `init()` function and verify if `$state.current.name == 'campaignEditConfirm'`. Thanks for information. – Alex M. Mar 09 '15 at 19:09
  • It isn't? You've now got a way to get your state parameters and your full state name. What's missing? – HankScorpio Mar 09 '15 at 19:10
  • I wanted to get route params that aren't variables without split URL by `/`, if possible. – Alex M. Mar 09 '15 at 19:11
  • 1
    Ah ok. For future reference a "parameter" is a kind of variable. – HankScorpio Mar 09 '15 at 19:12
  • I see. My title is wrong. Actually, looking here http://stackoverflow.com/questions/20878335/how-do-i-parse-url-params-after-a-hash-with-angularjs they suggest to split `$location.hash()` string. That's what I want to avoid. – Alex M. Mar 09 '15 at 19:15