Skip to content

Instantly share code, notes, and snippets.

@tswaters
Created August 6, 2015 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tswaters/65ceec1c3a1d806b3ec9 to your computer and use it in GitHub Desktop.
Save tswaters/65ceec1c3a1d806b3ec9 to your computer and use it in GitHub Desktop.
defer controller initialization until after a $resolve function is resolved.

Not sure if this will at all come in handy, seems to me if the controller doesn't run it just won't show things. More of a starting point than anything else - without further ado, adding a $resolve function on a controller and have it resolve prior to controller initialization.

angular.module('resolve', [])
  .directive('resolveController', [
            '$controller', '$parse', '$injector', '$window',
    function($controller,   $parse,   $injector,   $window) {
      return {
        link: function(scope, elem, attrs) {
          var ctrlName = attrs.resolveController;
          var injectAs = attrs.resolveAs || 'data';
          var getter = $parse(ctrlName);
          var ctrl = getter(scope) || getter($window);
          if (!ctrl) {
            throw new Error(ctrlName + ' not found.');
          }
          if (!ctrl.$resolve) {
            throw new Error(ctrlName + ' has no $resolve function')
          }
          var $resolve = $injector.invoke(ctrl.$resolve);
          $resolve.then(function (data) {
            var $scope = {$scope: scope};
            $scope[injectAs] = data;
            $controller(ctrl, $scope);
          });
        }
      };
    }
  ])

Usage:

angular.module('test-app', ['resolve'])
  .controller('TestController', TestController)

TestController.$inject = ['$scope', '$q', 'test']
TestController.$resolve = ['$q', '$timeout', function ($q, $timeout) {
  var Defer = $q.defer();
  $timeout(function () {
    Defer.resolve('boom')
  }, 1500)
  return Defer.promise;
}]
function TestController () {
  console.log('controller initialized', arguments)
}
<body ng-app="test-app">
  <div resolve-controller="TestController" resolve-as="test">
  </div>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment