How can you manually enter route resolution data inside the controller?

I have 2 routes sharing a controller, data is required before loading the view, and others do not need the allowed data.

An example of a routing segment:

... when('/users', { controller: 'UsersCtrl', templateUrl: '/partials/users/view.html', resolve: { resolvedData : ['Accounts', function(Accounts) { return Accounts.get(); }] } }). when('/users/add', { controller: 'UsersCtrl', templateUrl: '/partials/users/add.html' }) ... 

Controller example:

 app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData', function($scope, Helper, resolvedData) { // this works for the first route, but fails for the second route with // unknown "resolvedDataProvider" console.log(resolvedData); }]); 

Is there a way to get resolvedData in the controller without explicitly using the solution name as a dependency? So check can be performed?

Using $ injector does not work. I would like to do something similar to:

 if ($injector.has('resolveData')) { var resolveData = $injector.get('resolveData'); } 

However, this does not work even for a route with the set resolveData ('/ users'):

 app.controller('UsersCtrl', ['$scope', 'Helper', '$injector', function($scope, Helper, $injector) { // this does not work -> fails with the unknown "resolvedDataProvider" as well $injector.get('resolvedData'); }]); 

Can this be done in angularjs? Or should I just create a new controller?

Thanks.

+8
javascript angularjs
source share
2 answers

Looks like I figured out where to go. Allowed data is part of $route . So you can access it using:

 app.controller('UsersCtrl', ['$scope', '$route', 'Helper', function($scope, $route, Helper) { if ($route.current.locals.resolvedData) { var resolvedData = $route.current.locals.resolvedData; } }]); 
+7
source share

If no other route is needed, simply enter undefined on this route:

router:

 when('/users', { controller: 'UsersCtrl', templateUrl: '/partials/users/view.html', resolve: { resolvedData : ['Accounts', function(Accounts) { return Accounts.get(); }] } }). when('/users/add', { controller: 'UsersCtrl', templateUrl: '/partials/users/add.html', resolve: { resolvedData: function() { return undefined; } } }) 

controller:

 app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData', function($scope, Helper, resolvedData) { if(resolvedData){ //set some scope stuff for it } else { //do what you do when there is no resolvedData } }]); 
+5
source share

All Articles