Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
up vote 11 down vote accepted

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.

share|improve this answer
    
I googled better, and watch "AngularJS MTV Meetup: Best Practices (2012/12/11)" 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 pastebin.com/g5GncAhY – airato Dec 13 '12 at 6:38

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.

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.