AngularJS 1.5.0 brings the $resolve property, designed to make it easier to pass the ngRoute resolve data into the view without the need to create a controller for directives. This property also works for regular views. So this works:
(function() {
function ConfigureRoutes($routeProvider) {
$routeProvider.
when('/test', {
templateUrl: 'test.html',
controller: 'TestController',
controllerAs: 'vm',
resolve: {
'stuff': ['$q', function($q) {
return $q.when([
{ id: 1, name: 'John' },
{ id: 2, name: 'Jake' }
]);
}]
});
}
app.config(['$routeProvider', ConfigureRoutes]);
})();
<pre>{{ $resolve.stuff | json }}</pre>
However, there are times when I have several resolve functions I want to pass into the controller to mutate before using in the view. Currently I do something like:
when('/test', {
...
resolve: {
'stuff_1': ...
'stuff_2': ...
}
});
app.controller('StuffController', ['stuff_1', 'stuff_2', function(stuff_1, stuff_2) {
this.stuff_1 = stuff_1;
this.stuff_2 = stuff_2;
}]);
Is there a way of accessing this new $resolve property without having to access the parameters individually? I've tried:
app.controller('StuffController', ['$scope', function($scope) {
this.stuff_1 = $scope.$resolve.stuff_1; // $scope.$resolve == undefined
}]);
app.controller('StuffController', ['$resolve', function($resolve) {
this.stuff_1 = $resolve.stuff_1; // injector error
}]);
EDIT:
For those who may find this in the future, you can access this $resolve object a different way in your controller:
app.controller('TestController', function($route) {
this.$resolve = $route.current.locals;
});
So the decision was made to not attach $resolve before the controller is instantiated.
The decision was also made not to made $resolve and injectable. This can be achieved using $q.all() as a single resolve function, like so:
function config($routeProvider) {
$routeProvider.when('/',
controller: 'TestController',
controllerAs: 'vm',
template: 'test.html',
resolve: {
$resolve: function($q) {
return $q.all({
local_1: $q.when(),
local_2: $q.when()
});
}
});
}
Or if you want to have a forked version, see the PRs at ($scope.$resolve before controller)[https://github.com/angular/angular.js/pull/14135]
($resolve as injectable) [https://github.com/angular/angular.js/pull/14136]