0

I'm trying to access the current template URL when I change states in the template's controller.

The routes:

lrdcom.config(
    function($stateProvider, $urlRouterProvider, $locationProvider, stringUtilsProvider) {  
        $stateProvider
            .state(
                'docs',
                {
                    templateUrl: function($stateParams) {
                        return 'src/pages/' + $stateParams.doc + '.html';
                    },
                    url: '/docs/:doc'
                }
            );
    }
);

In the controller, I'd like to know what the templateURL actually returns:

pageViewer.controller(
    'pageViewerController',
    function($scope, $location, $state) {
        // how to get current url of template?
    }
);

As in, if the templateURL returned src/pages/mydoc.html how would i get that url from the controller?

I've looked at a number of SO answers suggesting accessing $route, or $state in the controller but I still cannot get it.

2 Answers 2

1

Have you tried this yet?

$state.current.templateurl

Otherwise do a console.log($state.current) and see if you can find your data there.

Edit:

I just tested it and it works, but note the capital 'U' in 'Url', so like this:

$state.current.templateUrl
Sign up to request clarification or add additional context in comments.

1 Comment

You're correct that I can do that. However, I set a function for templateUrl, so getting $state.current.templateUrl returned a function instead of a string. To get it to work, all I had to do was pass back in $stateParams like so: $state.current.templateUrl($stateParams). Thanks.
1

Why not including $stateParams as as service for the controller and access the doc param in the controller and compose the url again?

pageViewer.controller('pageViewerController', function($scope, $location, $stateParams) {
       // how to get current url of template?
       var url = 'src/pages/' + $stateParams.doc + '.html';
    }
);

Important $stateParams Gotcha

In state controllers, the $stateParams object will only contain the params that were registered with that state. So you will not see params registered on other states, including ancestors.

$stateProvider.state('contacts.detail', {
        url: '/contacts/:contactId',   
        controller: function($stateParams){
        $stateParams.contactId  //*** Exists! ***//
}
 }).state('contacts.detail.subitem', {
      url: '/item/:itemId', 
      controller: function($stateParams){
      $stateParams.contactId //*** Watch Out! DOESN'T EXIST!! ***//
      $stateParams.itemId //*** Exists! ***//  
  }

})

You can also find the above example on this page URL Routing

1 Comment

Thanks for answer. Yah in spirit of DRY, I was hoping to avoid recreating that logic and to just pull in the string from somewhere.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.