Vaibhav Pachauri
Vaibhav Pachauri

Reputation: 2671

UI-Router | Inject a service(or the resolved object) in the template function of the nested views

I have a scenario where I want to render the template only when some condition is met(on the basis of data we get from the REST call). So, I did the following :

My Code (by injecting the factory into the template function):

.state('dashboard.deal.xyz', {
    url: "/xyz/:dealId",
    resolve: {
      permissions: function(dealUnit, $state) {
        console.log('Inside the resolve of permissions :::', $state.params.dealId);
        return dealUnit.getUnitPermissions('123412341234DealId');
      }
    },
    views: {
      "viewA": {
        template: function(dealUnit) {
        //Here I want to inject either 'permissions' (the resolve object)
        //or the 'dealUnit' factory which gets me the permissions from the server directly.
        return '<h1>return the template after getting the permissions resolve object</h1>';
       }
      },
      "viewB": {
        template: "viewB"
      }
    }
  })

My 'dealUnit' factory is working fine and returns an object when I use it inside the 'resolve' of the state. But, that factory is not being injected when I inject it inside the template function of the nested view.

Am I doing it correctly? And if not then how should I go about doing it ?

Upvotes: 2

Views: 622

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

In case, we want to do some "magic" before returning the template... we should use templateProvider. Check this Q & A:

Trying to Dynamically set a templateUrl in controller based on constant

Because template:... could be either string or function like this (check the doc:)

$stateProvider

template

html template as a string or a function that returns an html template as a string which should be used by the uiView directives. This property takes precedence over templateUrl.

If template 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

template: function(params) {
    return "<h1>generated template</h1>"; }

While with templateProvider we can get anything injected e.g. the great improvement in angular $templateRequest. Check this answer and its plunker

templateProvider: function(CONFIG, $templateRequest) {
    console.log('in templateUrl ' + CONFIG.codeCampType);

    var templateName = 'index5templateB.html';

    if (CONFIG.codeCampType === "svcc") {
         templateName = 'index5templateA.html';
    } 

    return $templateRequest(templateName);
},

Upvotes: 1

Related Questions