Angular-UI-Router - 获取动态模板的内容 [英] Angular-UI-Router - getting content of dynamic template

查看:22
本文介绍了Angular-UI-Router - 获取动态模板的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular-ui-router 构建一个 angular 应用程序.后端有一个 REST api,它为我提供基于票证 ID 的表单的 url.在 app.js 中,我想根据对此 REST 服务的查询动态设置模板.示例:

I am building an angular app using angular-ui-router. The backend has a REST api that gives me the url to a form based on a ticket id. In app.js, I want to dynamically set the template based on a query to this REST service. Example:

$stateProvider
  .state('form', {
    url: '/form/:id',
    templateProvider: function ($resource, formResolver, $stateParams) {

      //formResolver calls the REST API with the form id and gets back a URL.
      return formResolver.resolve($stateParams.id).then(function(url) {
        return $resource(url).get();
      };

    },
    controller: 'MyCtrl'
  });

问题是我最终返回了一个 promise,而 templateProvider 需要一串内容.我想做的只是返回网址:

The problem is that I end up returning a promise and templateProvider requires a string of content. What I would like to do is just return the url:

$stateProvider
  .state('form', {
    url: '/form/:id',

    //I would like to inject formResolver, but I can't
    templateUrl: function (stateParams, formResolver) {
      return formResolver.resolve(stateParams.id);
    },
    controller: 'MyCtrl'
  });

但是当我按照 https:/使用 templateUrl 而不是 templateProvider 时,我没有得到依赖注入/github.com/angular-ui/ui-router/wiki#wiki-templates,我仍然有它返回承诺的问题.我在想,也许我唯一的解决方案是不使用 promise api.

But I don't get dependency injection when using templateUrl instead of templateProvider as per https://github.com/angular-ui/ui-router/wiki#wiki-templates, and I still have the problem of it returning a promise. I am thinking maybe my only solution is not to use the promise api.

推荐答案

结果证明我使用 $resource 的方式有问题.我仍然不确定是什么.通过查看 angular-ui-router 的源代码,函数 can 返回一个 promise.我最终从 https://github.com/angular 复制了一些代码-ui/ui-router/blob/master/src/templateFactory.js 以获取以下内容,该方法有效:

Turns out there was something wrong with the way I was using $resource. I'm still not sure what. From looking at the source for angular-ui-router, the function can return a promise. I ended up copying some of the code from https://github.com/angular-ui/ui-router/blob/master/src/templateFactory.js to get the following, which works:

    templateProvider: function ($http, formService, $stateParams) {
      return formService.getFormUrl($stateParams.id).then(function(url) {
        return $http.get(url);
      }).then(function(response) {
        return response.data;
      })

这篇关于Angular-UI-Router - 获取动态模板的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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