Scope of all controllers not saving in the service in routing -Angularjs
<p>I'm new to angular js. I was trying to save and share the scope of two different controllers.</p>

<p>Below is my script and views.</p>

<p>script.js:</p>

<pre><code>var app = angular.module('app', ['ngRoute']);

app.run(function ($rootScope) {
    $rootScope.$on('scope.stored', function (event, data) {
        console.log("scope.stored", data);
    });
});

app.controller('FirstController', function($scope) {
$scope.counter = 0;
$scope.add = function(amount) { $scope.counter += amount; };
$scope.subtract = function(amount) { $scope.counter -= amount; };
});


app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/v1', {
templateUrl: 'views/v1.ejs',
controller: 'controller1'
}).
when('/v2', {
templateUrl: 'views/v2.ejs',
controller: 'controller2'
})

}]);


app.controller('controller1', function($scope,Scopes) {
Scopes.store('controller1',$scope);
$scope.data = "controller1";
$scope.buttonClick = function () {
console.log( Scopes.get('controller2').data);
};
});

app.controller('controller2', function($scope,Scopes) {
Scopes.store('controller2',$scope);
$scope.data = "controller2";
$scope.buttonClick = function () {
console.log( Scopes.get('controller1').data);
};
});



app.factory('Scopes', function ($rootScope) {
    var mem = {};

    return {
        store: function (key, value) {
            $rootScope.$emit('scope.stored', key);
            mem[key] = value;
        },
        get: function (key) {
            return mem[key];
        }
    };
});
</code></pre>

<p>index.html:</p>

<pre><code>&lt;!doctype html&gt;
&lt;html ng-app="app"&gt;
  &lt;head&gt;
&lt;script src="js/angular.min.js"&gt;&lt;/script&gt;
&lt;script src="js/angular-route.min.js"&gt;&lt;/script&gt;
&lt;script src="js/script.js"&gt; &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;a href='#v1'&gt;View1&lt;/a&gt;
    &lt;a href='#v2'&gt;View2&lt;/a&gt;
    &lt;div ng-view&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>v1.ejs:</p>

<pre><code>&lt;div ng-controller="controller1"&gt;
 {{data}}
 &lt;br&gt;
 &lt;button ng-click="buttonClick()"&gt;Clickme!&lt;/button&gt;
&lt;/div&gt;
</code></pre>

<p>v2.ejs:</p>

<pre><code>&lt;div ng-controller="controller2"&gt;
 {{data}}
 &lt;br&gt;
 &lt;button ng-click="buttonClick()"&gt;Clickme!&lt;/button&gt;
&lt;/div&gt;
</code></pre>

<p>The problem is:</p>

<p>Whenever the page is loaded, #/v1 is triggered.
If i click on 'Clickme', JUST AFTER THE PAGE LOADS, Error: Scopes.get(...) is undefined is fired.</p>

<p>But, if i navigate to #/v2 and then to #/v1, the scopes are getting stored and the error is NOT fired.</p>

<p>Is there is some problem with with routeProvider? All the controllers wont be loaded at on-load event?</p>

<p>Please help me on this.</p>