2

I'm trying to wait for the provider to finish initializing before ui-router goes on to load the state.

Every time you enter the state the camera should be enabled, and whenever it is left disabled again. I put this into a provider because it needs to be usable at the module.config level:

.provider("Camera", function CameraProvider() {
  function init() {
    //async enableCamera
  }
  function exit() {
    //disableCamera
  }
  function $get() {
    return { init: init, exit: exit };
  }
});

and the state:

var cam = DubCameraProvider.$get(); // this is a hack, but I don't know how to
$stateProvider
.state("CameraState", {
  url: "/camera",
  onEnter: cam.init,
  onExit: cam.exit,
  views: {
    "view": {
        // template: ...,
      controller: "ControllerUsingCamera"
  }
 }

I tried using $q to create a promise and the using resolve to wait for that, but at the module.config level $q cannot be injected (or I just don't know how to?).

How can I solve this?

s-ol
  • 1,674
  • 17
  • 28

2 Answers2

1

resolve comes with dependency injection. You could do:

$stateProvider.state("CameraState", {
    url: "/camera",
    onEnter: cam.init,
    onExit: cam.exit,
    views: {
        "view": {
            // template: ...,
            controller: "ControllerUsingCamera"
        }
    },
    resolve: {
        somethingAsync: function($q) {
            var promise = $q.all( /*bunch of promises*/ );
            return promise;
        }
    }
}
Mosho
  • 7,099
  • 3
  • 34
  • 51
1

$q can be injected in the resolve object of your state without a problem:

Config:

angular.module('app').config([
    '$stateProvider',
    '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise('/');
        $stateProvider.state('root', {
            'url': '/',
            'controller': 'rootController',
            'templateUrl': 'root.html',
            'resolve': {
                'data': [
                    '$q',
                    '$timeout',
                    function ($q, $timeout) {
                        var deferred = $q.defer();
                        $timeout(function() {
                          deferred.resolve({
                            'value': 'Foo'
                          });
                        }, 5000);
                        return deferred.promise;
                    }
                ]
            }
        });
    }
]);

Controller:

angular.module('app').controller('rootController', [
    '$scope',
    'data',
    function ($scope, data) {
        $scope.value = data.value;
    }
]);

Straight from the documentation on their wiki: https://github.com/angular-ui/ui-router/wiki#resolve

Here's a working example on Plunker: http://plnkr.co/edit/kJ99Hi0qWx7DJxOVzxgA?p=preview

iH8
  • 27,722
  • 4
  • 67
  • 76
  • not exactly what I was looking for but got me on Track. Marking as final answer because it is more detailed than the one below. – s-ol Feb 02 '15 at 00:08