如何将服务注入 AngularJS 的 UI-Router templateUrl 函数? [英] How to inject a service into AngularJS's UI-Router templateUrl function?

查看:23
本文介绍了如何将服务注入 AngularJS 的 UI-Router templateUrl 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让 AngularJS 的 UI-Router 接收定义的状态(即项目"),如果没有匹配,则默认为根"状态.root"状态应使用远程 API (Firebase) 进行检查,并根据结果加载相应的视图.

I'm trying to have AngularJS' UI-Router pick up on the defined states (i.e. "project") and if none match, default to the "root" state. The "root" state should check with a remote API (Firebase) and based on the result load the appropriate view.

以下示例不满足其中任何一个要求:

The example below doesn't accomplish either of those requirements:

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

1) "http://website.com/project" is matched to the "root" state, and not (the previously defined) "project" state.

2) "templateUrl" 函数中未定义 "fbutil",无法注入.

2) "fbutil" is not defined in the "templateUrl" function, and cannot be injected.

请帮我解决这些问题.

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:

We cannot use templateUrl here - as stated in the doc:

如果 templateUrl 是一个函数,它将使用以下参数调用:

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

{array.} - 通过应用当前状态从当前 $location.path() 中提取的状态参数

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

传入 templateUrl 的参数是固定的.

The parameters coming to templateUrl are fixed.

所以,我们必须使用templateProvider

功能

返回 HTML 内容字符串的提供程序函数.

Provider function that returns HTML content string.

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

检查:

这篇关于如何将服务注入 AngularJS 的 UI-Router templateUrl 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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