且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有可能加载通过AJAX请求模板UI的路由器角?

更新时间:2023-11-03 16:06:40

我们应该的(在这种情况下)的使用 TemplateProvider 。小从DOC举:

模板


  

TemplateUrl 结果
  ... templateUrl 也可以是返回URL的功能。 它需要一个preSET参数, stateParams ,这是不注入。


  
  

TemplateProvider 结果
  或者你也可以使用模板提供商函数可以注射,先后获得当地人,并且必须返回HTML模板,像这样的:


块引用>
  $ stateProvider.state('联系人',{
  templateProvider:函数($超时,$ stateParams){
    返回$超时(函数(){
      回归'< H1>' + $ stateParams.contactId +'< / H1>'
    },100);
  }
})

和还有更多。

我们可以使用合作真的很强大

$ templateRequest 一>

在这个Q&放大器; A 根据塞从基于蛞蝓 API Ajax调用。加载视图角度UI-路由器动态路由)的,我们可以看到这么简单的 templateProvider 确定指标

  .STATE('混合',{
    // /约翰 - 史密斯
    网址:'/:蛞蝓,
    templateProvider:['型','$ templateRequest',
      功能(类型,templateRequest)
      {
        VAR tplName =tpl.partial-+类型+。html的;
        返回templateRequest(tplName);
      }
    ]

和的结果也chached ...

有一些其他的链接,类似的问答集A,包括工作示例

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?

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