UI-Router
is different than Angular
's ngRoute
. It supports everything the normal ngRoute
can do as well as many extra functions.
I am changing my Angular
app from ngRoute
to UI-Router
. But I cannot quite figure out how to inject resolve
function programmatically - the piece of code that I use outside Controller
and config
.
So, with standard Angular
's ngRoute
I can dynamically inject my resolve promise
in the Angular
run block:
app.run(function ($route) {
var route = $route.routes['/'];
route.resolve = route.resolve || {};
route.resolve.getData = function(myService){return myService.getSomeData();};
});
Now how do I inject resolve promise in a similar way using UI-Router
? I tried passing $stateProvider
to get access to state
s but that was failing for me.
angular.module('uiRouterSample').run(
[ '$rootScope', '$state', '$stateProvider'
function ($rootScope, $state, $stateProvider) {
//$stateProvider would fail
You can use resolve
to provide your controller with data before it loads the next state. To access the resolved objects, you will need to inject them into the controller as dependencies.
Let's use a shopping list application as an example. We'll start by defining our application module, and including ui.router
as a dependency.:
angular.module('myApp', ['ui.router']);
We now want to define the module that will be specific to the shopping list page of our application. We'll define a shoppingList
module, include the states for that module, a resolve for that state, and the controller.
Shopping List Module
angular.module('myApp.shoppingList').config(function ($stateProvider) {
$stateProvider.state('app.shoppingList', {
url: '/shopping-list',
templateUrl: 'shopping-list.html',
controller: 'ShoppingListController',
resolve: {
shoppingLists: function (ShoppingListService) {
return ShoppingListService.getAll();
}
}
});
});
We now can inject our resolved objects into our controller as dependencies. In the above state, I am resolving an object to the name shoppingLists
. If I want to use this object in my controller, I include it as a dependency with the same name.
Shopping List Controller
angular.module('myApp.shoppingList').controller('ShoppingListController', function ($scope, shoppingLists) {
$scope.shoppingLists = shoppingLists;
});
For additional details read the Angular-UI Wiki, which includes an in-depth guide to using resolve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With