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

非 Y 不嫁゛ 提交于 2019-12-10 14:06:23

问题


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" is matched to the "root" state, and not (the previously defined) "project" state.

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

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

回答1:


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

templateUrl (optional)

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

The parameters coming to templateUrl are fixed.

So, we have to use templateProvider

templateProvider (optional)

function

Provider function that returns HTML content string.

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

Check:

  • 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


来源:https://stackoverflow.com/questions/33838313/how-to-inject-a-service-into-angularjss-ui-router-templateurl-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!