Angular UI Router:根据父解析对象决定子状态模板 [英] Angular UI Router: decide child state template on the basis of parent resolved object

查看:30
本文介绍了Angular UI Router:根据父解析对象决定子状态模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 app.js 文件-我有一个父状态和两个子状态.两个子视图都需要该对象.

this is my app.js file- i have one parent state and two child states. Both the child views need the object.

    states.push({
      name: 'parentstate',
      url: '/parent/:objId',
      abstract: true,
      templateUrl: 'views/parentview.html',
      controller: function() {},
      resolve: {
        obj: function(OBJ, $stateParams) {
          return OBJ.get($stateParams.objId);
        }
      }
    });

我想用这个解析的 obj 来决定子模板

i want to use this resolved obj to decide child template

    states.push({
      name: 'parentstate.childs',
      url: '/edit',
      views: {
        "view1@parentstate": {
          templateUrl: 'views/view1',
          controller: 'view1Ctrl'
        },
        "view2@parentstate": {
          templateUrl: function(obj) {
            if (obj.something == something) {
              return "views/view2first.html";
           } else {
              return 'views/view2second.html';
            }
          },
          controller: 'view2Ctrl'
        }
      }  
    });

我怎样才能做到这一点?

How can i achieve this?

推荐答案

有一个有效的示例.我们应该使用 templateProvider 而不是 templateUrl.这是新的状态定义:

There is a working example. Instead of templateUrl we should use the templateProvider. This is new state def:

  $stateProvider
    .state('parentstate.childs', {
      url: '/edit',
      views: {
        "view1@parentstate": {
          templateUrl: 'views.view1.html',
          controller: 'view1Ctrl',
        },
        "view2@parentstate": {
          templateProvider: function($http, $stateParams, OBJ) {

            var obj = OBJ.get($stateParams.objId);
            var templateName = obj.id == 1
              ? "views.view2.html"
              : "views.view2.second.html"
              ;
        
            return $http
                  .get(templateName)
                  .then(function(tpl){
                    return tpl.data;
                  });
          },
          controller: 'view2Ctrl',
        }
      }
    });

我们为什么要使用这种方法?如此处所述:

Why are we using this approach? as documented here:

TemplateUrl
... templateUrl 也可以是一个返回 url 的函数.它需要一个预设参数,stateParams,它没有被注入.

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

模板提供者
或者,您可以使用 模板提供程序 函数,该函数可以被注入,可以访问本地人,并且必须返回模板 HTML,如下所示:

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

在这个工作 plunker 中检查基于 TemplateProvider 的解决方案

Check the TemplateProvider based solution in this working plunker

这篇关于Angular UI Router:根据父解析对象决定子状态模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆