Angular-UI-Router - getting the contents of a dynamic template

I am creating an angular application using angular -ui-router. The backend has a REST api that gives me the url of the form based on the ticket id. In app.js, I want to dynamically install a template based on a request to this REST service. Example:

$stateProvider .state('form', { url: '/form/:id', templateProvider: function ($resource, formResolver, $stateParams) { //formResolver calls the REST API with the form id and gets back a URL. return formResolver.resolve($stateParams.id).then(function(url) { return $resource(url).get(); }; }, controller: 'MyCtrl' }); 

The problem is that I am returning a promise, and templateProvider requires a content string. What I would like to do is simply return the url:

 $stateProvider .state('form', { url: '/form/:id', //I would like to inject formResolver, but I can't templateUrl: function (stateParams, formResolver) { return formResolver.resolve(stateParams.id); }, controller: 'MyCtrl' }); 

But I don't get dependency injection when using templateUrl instead of templateProvider as per https://github.com/angular-ui/ui-router/wiki#wiki-templates and I still have a problem returning the promise. I think maybe my only solution is not to use the promise of api.

+6
source share
2 answers

It turns out that something is wrong with the way I used $resource . I'm still not sure what. From looking at the source for angular -ui-router, a function can return a promise. I ended up copying some code from https://github.com/angular-ui/ui-router/blob/master/src/templateFactory.js to get the following:

  templateProvider: function ($http, formService, $stateParams) { return formService.getFormUrl($stateParams.id).then(function(url) { return $http.get(url); }).then(function(response) { return response.data; }) 
+8
source

The function for the Provider template can return a promise from $ resource, but in the end it should return a string.

 templateProvider: function (SomeService) { var promise = SomeService.get().$promise; promise.then(function (data) { console.log(data) // it has to be string! }); return promise; } 

If there is an object, one solution would be another promise.

 templateProvider: function (SomeService, $q) { var defer = $q.defer(); var promise = SomeService.get().$promise; promise.then(function (data) { console.log(data) // let say this is {html: '<p>some template</p>'} defer.resolve(data.html); }); return defer.promise; } 

SomeService returns $ resource.

0
source

All Articles