AngularJS remember DOM state between views

423 views Asked by At

It seems like Angular re-renders an entire view when a route changes. See this example: http://jsfiddle.net/RSHG8/1/

html:

<div class="nav">
    <a href="#/one">One</a><a href="#/two">Two</a>
</div>
<div ng-app="app" id="ng-app">
    <div ng-view=ng-view></div>
</div>

var app = angular.module('app', []);

js:

app.config(function ($routeProvider) {
    $routeProvider.when('/one', {
        template: 'Template {{template}}<br>Enter some text: <input type="text" /> then click "Two"',
        controller: 'one'
    })
        .when('/two', {
        template: 'Template {{template}}<br>Click back to view "One" to see changes undone',
        controller: 'two'
    })
        .otherwise({
        redirectTo: '/one'
    });
});

app.controller("one", function ($scope) {
    $scope.template = "One";
});

app.controller("two", function ($scope) {
    $scope.template = "Two";
});

Text entered by the user is forgotten when the switching between views. This will be a problem with non-angular stuff too. E.g. a jQuery expand-collapse plugin. If a user expands a certain number of elements, leaves the view and comes back, the state will be reset to everything collapsed.

Is it possible to get Angular to simple show / hide views, rather than wipe an re-render when routes change?

1

There are 1 answers

2
XPX-Gloom On

You can try assigning a ng-model to the input tag and store the value in a parent controller.

HTML

<div class="nav">
    <a href="#/one">One</a><a href="#/two">Two</a>
</div>
<div ng-app="app" id="ng-app">
    <div controller="AppCtrl">
        <div ng-view=ng-view></div>
    </div>
</div>

var app = angular.module('app', []);

JS

app.config(function ($routeProvider) {
        $routeProvider.when('/one', {
            template: 'Template {{template}}<br>Enter some text: <input type="text" ng-model="$parent.inputValue" /> then click "Two"',
            controller: 'one'
        })
            .when('/two', {
            template: 'Template {{template}}<br>Click back to view "One" to see changes undone',
            controller: 'two'
        })
            .otherwise({
            redirectTo: '/one'
        });
    });

    app.controller("AppCtrl", function AppCtrl($scope) {
        $scope.inputValue = "";
    });

    app.controller("one", function ($scope) {
        $scope.template = "One";
    });

    app.controller("two", function ($scope) {
        $scope.template = "Two";
    });