Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: two way data bindings and controller reload

Tags:

angularjs

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?

like image 967
airato Avatar asked Dec 12 '12 13:12

airato


1 Answers

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.

like image 122
Artem Andreev Avatar answered Sep 20 '22 22:09

Artem Andreev