如何将服务注入 AngularJS 的 UI-Router templateUrl 函数?

How to inject a service into AngularJS's UI-Router templateUrl function?

我正在尝试让 AngularJS' UI-路由器在定义的状态(即 "project")上拾取,如果 none 匹配,则默认为"root" 状态。 "root" 状态应使用远程 API (Firebase) 检查并根据结果加载适当的视图。

下面的例子没有满足任何一个要求:

1) "http://website.com/project" 匹配到 "root" 状态,而不是(之前定义的)"project" 状态。

2)"fbutil"在"templateUrl"函数中没有定义,无法注入

请帮我解决这些问题。

angular.module('app')

.config(['$stateProvider', '$urlRouterProvider',
 function($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('project', {
            url: '/project',
            views: {
                'mainView': {
                    controller: 'ProjectCtrl as project',
                    templateUrl: '/views/project.html'
                }

            }
        })
        .state('root', {
            url: '/:id',
            views: {
                'mainView': {
                    templateUrl: function($stateParams, fbutil) {
                        var ref = fbutil.ref('user_data', id);
                        ref.once('value', function(dataSnapshot) {
                            return '/views/' + dataSnapshot.$val() +'.html';
                        }, function(error) {
                            return '/views/root.html';
                        });
                    }
                }
            }
        })
 }
]);

我们不能在这里使用 templateUrl - 如 doc:

中所述

templateUrl (可选)

If templateUrl is a function, it will be called with the following parameters:

{array.} - state parameters extracted from the current $location.path() by applying the current state

传入templateUrl的参数是固定的。

所以,我们必须使用templateProvider

模板提供者(可选)

function

Provider function that returns HTML content string.

templateProvider:
  function(MyTemplateService, params) {
    return MyTemplateService.getTemplate(params.pageId);
  }

检查:

  • Angular UI Router: decide child state template on the basis of parent resolved object
  • Angular and UI-Router, how to set a dynamic templateUrl
  • Changing Navigation Menu using UI-Router in AngularJs