My Technical Notes

Friday, 9 October 2015

Angular Route - State maintenance

This example demonstrates how to maintain `$scope` state for a specific route. We define a service `scopeContainer` that we use to store and retrieve `$scope` variables.


<!DOCTYPE html>

<html>
<head>
    <title></title>
</head>
<body ng-app="app">
    <div>
        <script type="text/ng-template" id="templateOne.html">
            <div>
                <a href="javascript:void(0)" ng-click="btnClick()">Increment integer value: </a> {{model.intVal}}
            </div>
            <a href="#pathTwo">Go to path two</a>
        </script>
        <script type="text/ng-template" id="templateTwo.html">
            <div>
                this is template two!
            </div>
            <a href="#pathOne">Go to path one</a>
        </script>
    </div>

    <div>
        <div ng-view></div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
    <script>
        var app = angular.module('app', ['ngRoute']);

        app.config(function ($routeProvider) {
            $routeProvider
                .when('/pathOne', { templateUrl: 'templateOne.html', controller: 'controllerOne' })
                .when('/pathTwo', { templateUrl: 'templateTwo.html', controller: 'controllerTwo' })
                .otherwise({ redirectTo: '/pathOne' });
        });

        app.service('scopeContainer', function () {

        });

        app.controller('controllerOne', function ($scope, scopeContainer) {
            $scope.model = scopeContainer.controllerOneModel || { intVal: 0 };

            $scope.btnClick = function () {
                $scope.model.intVal = $scope.model.intVal + 1;
            }

            $scope.$on("$destroy", function () {
                scopeContainer.controllerOneModel = $scope.model;
            });
        });

        app.controller('controllerTwo', function ($scope, scopeContainer) {

        });
    </script>
</body>
</html>

No comments: