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?
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.
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.
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