角UI路由器:父解析对象的基础上,决定孩子状态模板 [英] Angular UI Router: decide child state template on the basis of parent resolved object

查看:109
本文介绍了角UI路由器:父解析对象的基础上,决定孩子状态模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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?

推荐答案

有一个工作例如。取而代之的 templateUrl 我们应该使用 templateProvider 。这是新的状态DEF:

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的功能。 它需要一个preSET参数, stateParams ,这是不注入。

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

TemplateProvider 结果
  或者你也可以使用模板提供商函数可以注射,先后获得当地人,并且必须返回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

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

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