Search code examples
javascriptangularjsangular-ui-routerangular-uistate

Angular UI-Router - using "resolve" directly on template url


I am using UI-Router and want to change routing to be 'component based'. So Instead of defining a controller / template I want to use it like this:

.state('issue', {
    url: '/someUrl/:number',
    template: '<my-directive></my-directive>',
    resolve: {
      data: function(dataService) {
        return dataService.getData().then(function(response) {
            console.log(response.data);
            return response.data;
        });
      }
    }
 })

Now, I know that with Angular's ngRoute I can use resolved data directly in the template, for example:

 $routeProvider
      .when('/', {
        template: `<my-directive data="resolve.data"></my-directive>`,
        resolve: {
          data: function (dataService) {
            return dataService.getData();
          }
        }
      }) 

I couldn't do it using UI-Router (value was undefined).

Am I doing something wrong? Is it possible using ui-router?


Solution

  • The point with UI-Router is - result of resolve is available for a controller (related to template). So, we could do it like this:

    .state('issue', {
        url: '/someUrl/:number',
        template: '<my-directive data="stateCtrlData"></my-directive>',
        controller: function($scope, data) { $scope.stateCtrlData = data },
        resolve: {
          data: function(dataService) {
            return dataService.getData().then(function(response) {
                console.log(response.data);
                return response.data;
            });
          }
        }
      })
    

    The data are passed into controller and from its scope we pass it to directive.