I'm using angular-ui ui-router for a web-app. I have a state/view configuration like this:
...
.state('parentState', {
url:'/:id',
views: {
'main@parent': {
controller: 'ParentMainCtrl',
},
'sub@parent': {
controller: 'ParentSubCtrl',
},
},
})
...
Now, I need to share data between the two states, main
and sub
. One way is to add a resolve
to parentState
and inject the dependency into the controllers of the views, but then I won't be able to do a data-binding between the two views. I tried adding a data
attribute to parentState
, but seems the children views do not inherit it. What would be a way to do a two-way data binding between the sibling views inside this state?
In my opinion, view routers shouldn't be responsible for data.
You should create a service that contains your data and operations to modify that data, then inject that service into your two controllers.
The nice thing about this too is that if you wanted to share this data source with even more modules besides ParentMainCtrl
and ParentSubCtrl
, you could add the service as a dependency to those modules.
var myApp = angular.module('myApp', []);
angular.module('myApp').factory('sharedService', ['$http',
function($http) {
return {
data: {},
// functions to get/set properties in data
}
}
]);
angular.module('myApp').controller('ParentMainCtrl', ['$scope', 'sharedService',
function($scope, sharedService) {
$scope.data = sharedService.data;
}
]);
angular.module('myApp').controller('ParentSubCtrl', ['$scope', 'sharedService',
function($scope, sharedService) {
$scope.data = sharedService.data;
}
]);
http://plnkr.co/edit/WHIWUQRJNAmhQQKKJDDl?p=preview
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