Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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';
                        });
                    }
                }
            }
        })
 }
]);
like image 958
Nikolay Gorb Avatar asked Sep 26 '22 03:09

Nikolay Gorb


1 Answers

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
like image 74
Radim Köhler Avatar answered Oct 03 '22 23:10

Radim Köhler