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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
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 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.