Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass variables to a controller from ui.router?

I have a page structured with some nested views, using ui.router and I would like to pass some data from the parent controller to the child controller, without injecting useless services into the child controller.

In my mind, something like these would be perfect

        state('home', {
            url: "/home",
            templateUrl: "parts/home.html",
            controller: "FatherController"
        }).
        state('home.child', {
            url: "/child",
            templateUrl: "parts/home/child.html",
            controller: "ChildController",
            params: {$scope.data = $rootScope.someData}
        })


Do you happen to know if there is a way to do this?

like image 519
domokun Avatar asked Dec 02 '22 17:12

domokun


2 Answers

If your child view is nested within the parent view, your child controller will automatically inherit the parent scope.

You should be able to access the parent controller's data directly from the child controller.

like image 129
Joseph Silber Avatar answered Dec 04 '22 07:12

Joseph Silber


Well, I guess you don't always have the choice to move the data to a parent controller or such.

My recommendation for this would be to use resolvers (https://github.com/angular-ui/ui-router/wiki#resolve) to do some magic.

Here's a sample on how it could be made to work:

var dataResolver = ['$scope', '$stateParams', 'Service',
    function($scope, $stateParams, Service) {
        Service.get($stateParams.objectId).then( function(obj) {
            $scope.myObject = obj;
            return obj;
        });
     };
 ];

 $stateProvider.state("foo.details", {
     "url": '/foo/:objectId', 
     "resolve": { "data": dataResolver },
     "controller": "SomeController",
     "template": "<ui-view />"
 )

And you magically get the $scope.obj data when the controller is instanciated, whatever how.

like image 28
vperron Avatar answered Dec 04 '22 05:12

vperron