0

I come here from this question Is it possible to load a template via AJAX request for UI-Router in Angular?

I wish to load a template for a given state using $http.

ui.router docs shows examples where both $timeout and $http are used within $stateProvider config, e.g.

Or you can use a template provider function which can be injected, has access to locals, and must return template HTML, like this:

$stateProvider.state('contacts', {   templateProvider: function
 ($timeout, $stateParams) {
   return $timeout(function () {
    return '<h1>' + $stateParams.contactId + '</h1>'
   }, 100);   
 } 
})

However, as I understand it, $stateProvider has to be configured during module.config phase, and $timeout is not available then. I cannot find any example which shows how to access $timeout (or $http) for $stateProvider exactly per the example provided by the docs.

Is there a way to access either $timeout or $http as defined in the docs? Do I configure state at another point? Is there an alternative way to do this which I'm overlooking?

dewd
  • 4,380
  • 3
  • 29
  • 43

1 Answers1

3

The templateProvider function itself is injected with the dependencies using injector service, and it has nothing to do with the config phase.

So you should be able to use $http simply by injecting it in the function. If you see the example, $timeout or $stateParams are also not available at the config phase, but they work fine in the templateProvider function.

For example, the below snippet returns the content of HTTPBin:

templateProvider: function($http) {
  return $http.get('https://httpbin.org/get')
    .then(function(response) {
      return JSON.stringify(response.data);
    });
  }

For more details, refer to this fiddle.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • Ah! Good point. I was trying to inject `timeout` into the config. No wonder. I shall try it without and if it works tick your answer and give +1. Thank you. – dewd Dec 08 '17 at 14:55
  • 1
    @dewd -- please see my updated answer for more details. – 31piy Dec 08 '17 at 15:07