0

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});
      },
    }
  })

})

1 Answer 1

1

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.

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

1 Comment

thank you! I knew it would be something simple I was missing.

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.