Angular ui-router templateProvider never called

2019-05-07 03:52发布

问题:

I need to pass a route parameter to the server responding with a template, so I'm trying to use a templateProvider per several articles/other stack overflow docs.

I'm not getting any javascript errors, but the following templateProvider method is never even executed. When the templateUrl property is not commented out, this route works fine.

$stateProvider
.state('org.contacts.add', {
  url: '/add',
  views: {
    'org@': {
      // templateUrl: '/templates/issues/add',
      controller: 'ContactsAddController',
      templateProvider: function($route, $templateCache, $http) {
          var url = '/templates/' + $route.current.params.org + '/contacts/add';
          $http.get(url, {cache: $templateCache}).then(function(html){
              return html;
          });
      }]
    }
  }
})

After some experimentation, it seems the $route was causing trouble. Taking that out and using $stateParams at least fires this code/controller.

However, while I see the ajax call firing and the proper html response, it's never loaded to the view.

    templateProvider: function ($stateParams, $http, $templateCache) {
        var url = '/templates/contacts/add';
        $http.get(url, {cache: $templateCache}).then(function(html){
            return html;
        });
    }

回答1:

I'm guessing you need to return a $promise for this to work. Check out the example used on the UI-Router wiki:

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

Notice the line that begins with return $timeout(.... Have you tried returning the $promise that is created by doing $http.get()?