4

I'm working on an angular 1.5 app that makes heavy use of ui-router.

We define our states like this:

$stateProvider
  .state('jobs', {
    url: '/jobs',
    template: '<ut-jobs></ut-jobs>',
});

Notice that the template for this page is a simple angular directive rather than a template string (or templateUrl) with a separate controller. Our directive's controllers are defined inline, like this:

angular.directive('utJobs', () => {
  return {
    templateUrl: 'jobs.html',
    controllerAs: 'jobs',
    controller: [() => {
      console.log('jobs directive loaded!');
    }],
  }
});

This lets us keep things nice and tidy, since our directive's controllers are close to the directive definition.

We would like to leverage ui-router's resolve feature to help simplify our resource fetching. However, since our state controllers aren't kept in $stateProvider.state definitions, I can't figure out for the life of me how to access the result of resolve (job in the above example.) Is there some kind of $resolve service that I could inject into the directive's controller to access the resolved resources? Am I missing something obvious? Or is ui-router not support this?

1 Answer 1

4

You have two options depending on your version of UI-Router.

If you are using ui-router 1.0.0-beta or greater

ui-router 1.0.0-beta allows for routed components, so your resolves would map directly with your directive's scope binding.

$stateProvider
  .state('jobs', {
    url: '/jobs',
    resolve: {
      jobs: (JobsService) => JobsService.getAll()
    }
    component: 'ut-jobs'
});

Then bind the resolve property to your .directive:

angular.directive('utJobs', () => {
  return {
    templateUrl: 'jobs.html',
    scope: {
      jobs: '<'
    },
    controllerAs: 'jobs',
    controller: () => {
      // do what you will this.jobs
    },
  }
});

If you are not using ui-router 1.0.0-beta

You will have to create a controller on your state and pass in the resource from your resolve, and then pass that into your directive.

$stateProvider
  .state('jobs', {
    url: '/jobs',,
    resolve: {
      jobs: (JobsService) => JobsService.getAll()
    },
    controller: function($scope, jobs) {
      $scope.jobs = jobs;
    },
    template: '<ut-jobs jobs="jobs"></ut-jobs>',
});

In this case, the jobs object on $scope is getting passed to your directive:

angular.directive('utJobs', () => {
  return {
    templateUrl: 'jobs.html',
    scope: {
      jobs: '<'
    },
    controllerAs: 'jobs',
    controller: [() => {
      // do what you will this.jobs
    }],
  }
});

Notes/Reading

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.