6

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?

airato
  • 101
  • 1
  • 6

2 Answers2

11

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.

Artem Andreev
  • 19,942
  • 5
  • 43
  • 42
  • I googled better, and watch "AngularJS MTV Meetup: Best Practices (2012/12/11)" http://www.youtube.com/watch?v=ZhfUv0spHCY So, as you said, the right decision is services. And no need to use $scope.watch if in html bindings use something with dot, like http://pastebin.com/g5GncAhY – airato Dec 13 '12 at 06:38
0

You could inject $rootScope into your controller and use it to store globally accessible variables, though you would still have the same issue watching for changes. You could create a directive which would inject your service into the current scope, and have it bind watch handlers in the scope as well.

  • 1
    You could create global variables, but it would be a terrible idea. Global variables should be used few and far between. See http://c2.com/cgi/wiki?GlobalVariablesAreBad. Use them wisely. – Ian Stanway Sep 14 '15 at 21:02