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

问题描述

我正在使用angular-ui-router构建一个角度应用程序。后端有一个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需要一串内容。我想做的就是返回url:

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

但是按照,我仍然有它返回承诺的问题。我想也许我唯一的解决方案就是不使用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的源代码,函数可以返回一个promise。我最终从得到以下内容,有效:

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 - 获取动态模板的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 01:47
查看更多