Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you manually inject route resolve data inside a controller?

I have 2 routes that share a controller, one needs data resolved prior to the view loading, and the other does not need the resolved data.

Routing segment example:

...
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 any way I can get the resolvedData in the controller without explicitly using the resolve name as a dependency? So a check can be performed?

Using the $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 the route that has the resolveData set ('/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?

Thank you.

like image 669
Alexandrin Rus Avatar asked Oct 07 '13 16:10

Alexandrin Rus


2 Answers

Looks like I figured out another way to go. The resolved data is part of the $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;
        }
}]);
like image 60
Alexandrin Rus Avatar answered Nov 12 '22 03:11

Alexandrin Rus


If the other route doesn't need it, just inject undefined on that 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
        }
}]);
like image 28
Fourth Avatar answered Nov 12 '22 04:11

Fourth