I am building an angular-app with ui-router where I have a parent view and a child view.
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/views/home/home.html',
controller: 'HomeController'
})
.state('new-assignment', {
url: '/new-assignment',
templateUrl: 'new-assignment.html',
controller: 'AssignmentController'
})
.state('new-assignment.new-client', {
url: '/new-client',
templateUrl: 'new-client.html',
controller: 'ClientController'
})
;
});
The child view is used (among other things) to create a new client. So, by clicking on 'create new client' in the main view. The state is change to 'new-assignment.new-client', and the side view is shown.
When the client is created I want to transition back to the parent view 'new-assignment' and pass along information with what client that have just been created.
The parent view could still have data in its own form (for creating assignment) and should naturally not be touched.
I can detect a change by '$stateChangeSuccess' event:
routerApp.controller('AssignmentController', function($scope, Assignment, Client, $log) {
$scope.clients = Client.clients;
$scope.$on('$stateChangeSuccess', function (e, toState, toParams, fromState, fromParams){
$log.log(fromState.name + ' -> ' + toState.name);
$log.log('toParams ');
$log.log(toParams);
$log.log('fromParams ');
$log.log(fromParams);
});
});
I have tried to pass info through
$state.go('^', data);
but without success...
But I don't understand how to pass data to the parent view. Any ideas?
Child view scope inherits from the scope of the parent view. So just define $scope.clients[]
array in the AssignmentController
. Then add the new client to that array in the ClientController
.
Take a look at this Plunker to see how the nested view scopes get access to their parent view scope.
Rudely I will answer my own question.
I decided to go with event messaging:
app.controller('ClientController', function ($scope, $state, ClientService) {
$scope.save = function (newClientData) {
var ret = ClientService.create(newClientData);
if (ret) {
// Pass newly created object to parent view.
$scope.$emit('clientCreated', newClientData);
// Then go to that state (closing child view)
$log.log($state);
if ($state.current.name === 'new-client')
return $state.go('home');
$state.go('^');
}
};
});
app.controller('AssignmentController', function ($scope, Assignment, ClientService) {
$scope.clients = ClientService.clients;
$scope.$on('clientCreated', function (e, data) {
$scope.clientSelected(data);
});
$scope.clientSelected = function (client) {
$log.log(client);
$scope.data.client = client;
$scope.data.clientName = client.name;
$scope.data.clientId = client.id;
}
});
This code is linked to the code in my question!
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