简体   繁体   English

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

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

I'm trying to have AngularJS' UI-Router pick up on the defined states (ie "project") and if none match, default to the "root" state. 我正在尝试让AngularJS的UI-Router选择已定义的状态(即“project”),如果没有匹配,则默认为“root”状态。 The "root" state should check with a remote API (Firebase) and based on the result load the appropriate view. “root”状态应检查远程API(Firebase)并根据结果加载相应的视图。

The example below doesn't accomplish either of those requirements: 以下示例未完成以下任一要求:

1) " http://website.com/project " is matched to the "root" state, and not (the previously defined) "project" state. 1)“ http://website.com/project ”与“root”状态匹配,而不是(先前定义的)“project”状态。

2) "fbutil" is not defined in the "templateUrl" function, and cannot be injected. 2)“fbutil”未在“templateUrl”函数中定义,并且无法注入。

Please help me resolve these issues. 请帮我解决这些问题。

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

We cannot use templateUrl here - as stated in the doc : 我们不能在这里使用templateUrl - 如文档中所述:

templateUrl (optional) templateUrl (可选)

If templateUrl is a function, it will be called with the following parameters : 如果templateUrl是一个函数,它将使用以下参数调用

{array.} - state parameters extracted from the current $location.path() by applying the current state {array。} - 通过应用当前状态从当前$ location.path()中提取的状态参数

The parameters coming to templateUrl are fixed. 进入templateUrl的参数是固定的。

So, we have to use templateProvider 所以,我们必须使用templateProvider

templateProvider (optional) templateProvider (可选)

function 功能

Provider function that returns HTML content string. 返回HTML内容字符串的Provider函数。

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

Check: 校验:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM