If use routing and controllers, then model not save his states between controller reload. Angular create controller instance and new scope on every route load.
For example, i type something in input that have ng-model="something", go to another route, then back to first route. All my typed text is lost.
I need simple two way data binding between routes changing. As simple as possible, like ko.observable in knockoutjs. Or implicitly like in angular within one controller. Maybe with singleton $scope for controller?
I found the way, when i create service for saving data between route changing, and inject it into controller. In controller's constructor i create model with value from service, and $scope.watch this model for changes, and on change i set model's value to service.
Is there any simpler way?
You are right - services is right way for doing this. You can use it like so:
app.js
app.factory('paginationService', function() {
return {
cur: 1,
total: 9,
pageSize: 8
};
});
app.controller('Page1Ctrl', function($scope, paginationService) {
$scope.pagination = paginationService;
});
Page1.html
<div ng-controller="Page1Ctrl">
<h2>Page1</h2>
<p>curPage: <input type="number" ng-model="pagination.cur" /></p>
</div>
See full example.
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