awwester
awwester

Reputation: 10172

Share resolve in Angular UI Router

I have various states that use the same resolve to load a timeLog into my controller $scope before the controller loads. I would like to not reproduce this code but share it between these views. I'm fairly new to JS frameworks, and especially Angular JS.

I'm having a hard time googling this and not finding any decent information. Maybe I'm searching incorrectly or not thinking about this correctly. Any Suggestions?

.config(function($stateProvider) {
$stateProvider
.state('tab.edit-log-summary', {
    url: '/logs/edit-log-summary/:timeLogId',
    views: {
      'tab-logs': {
        templateUrl: 'templates/logs/edit-log-summary.html',
        controller: 'EditLogSummaryCtrl'
      }
    },
    resolve: {
      timeLog: function(config, $stateParams, DailyLog) {
        return DailyLog.get({id: $stateParams.timeLogId});
      },
    }
  })

  .state('tab.edit-time-log', {
    url: '/logs/edit-time-log/:timeLogId',
    views: {
      'tab-logs': {
        templateUrl: 'templates/logs/edit-time-log.html',
        controller: 'EditTimeLogCtrl'
      }
    },
    resolve: {
      timeLog: function(config, $stateParams, DailyLog) {
        return DailyLog.get({id: $stateParams.timeLogId});
      },
    }
  })

})

Upvotes: 0

Views: 70

Answers (1)

Harris
Harris

Reputation: 1785

This really goes down to vanilla Javascript. The resolves are objects. Just define them as a single object somewhere above and pass it to the resolve property each time.

.config(['$stateProvider',function($stateProvider) {
var timeLogResolve = {
      timeLog: ['config','$stateParams','DailyLog',function(config, $stateParams, DailyLog) {
        return DailyLog.get({id: $stateParams.timeLogId});
      }]
    };

$stateProvider
.state('tab.edit-log-summary', {
    url: '/logs/edit-log-summary/:timeLogId',
    views: {
      'tab-logs': {
        templateUrl: 'templates/logs/edit-log-summary.html',
        controller: 'EditLogSummaryCtrl'
      }
    },
    resolve: timeLogResolve,
    }
  })

  .state('tab.edit-time-log', {
    url: '/logs/edit-time-log/:timeLogId',
    views: {
      'tab-logs': {
        templateUrl: 'templates/logs/edit-time-log.html',
        controller: 'EditTimeLogCtrl'
      }
    },
    resolve: timeLogResolve,
    }
  })

}])

One suggestion- use inline array notation for providing dependencies. This helps protect your code from breaking if you minify it. I did that myself in the demo above, but I leave it to your discretion to keep it.

Upvotes: 1

Related Questions