2

I know this might get an answer here, however that goes more for lazy loading implementation itself.

So, this is a typical UI-Router config block:

app.config(function($stateProvider, $urlRouterProvider, $injector) {
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'view_home.html',  // Actually SHOULD BE result of a XHR request ....
            controller: 'HomeCtrl'
        });
});

But what if I want to load such templateUrl when it's requested ($stageChangeStart) and it would be AJAX request based.

How should it be implemented? How are LARGE angular applications dealing with this?

1 Answer 1

5

We should (in this case) use TemplateProvider. Small cite from doc:

Templates

TemplateUrl
... templateUrl can also be a function that returns a url. It takes one preset parameter, stateParams, which is NOT injected.

TemplateProvider
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);
  }
})

And there is even more.

We can use cooperation with really powerful

$templateRequest

In this Q & A (Angular UI-Router dynamic routing based on slug from API Ajax Call. Load view based on slug) we can see so simple templateProvider defintion

.state('hybrid', {
    // /john-smith
    url: '/:slug',
    templateProvider: ['type', '$templateRequest',
      function(type, templateRequest) 
      {
        var tplName = "tpl.partial-" + type + ".html";
        return templateRequest(tplName);
      }
    ],

and the result is also chached...

There are some other links to similar Q & A, including working examples

Sign up to request clarification or add additional context in comments.

1 Comment

How do you access $timeout in the config phase, when $stateProvider is configured?? $timeout is being configured then too and is not available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.