'use strict';
angular
.module('demoApp', [])
.factory('shareService', shareService)
.controller('FirstCtrl', FirstCtrl)
.controller('SecondCtrl', SecondCtrl);
function FirstCtrl ($scope, shareService) {
shareService.store('FirstCtrl', $scope)
$scope.variableOne = 'First Controller Variable';
$scope.ctrl = 'First Controller';
$scope.getTwo = function() {
$scope.resTwo = shareService.get('SecondCtrl').variableTwo;
}
}
function SecondCtrl ($scope, shareService) {
shareService.store('SecondCtrl', $scope)
$scope.variableTwo = 'Second Controller Variable';
$scope.ctrl = 'Second Controller';
$scope.getOne = function() {
$scope.resOne = shareService.get('FirstCtrl').variableOne;
}
}
function shareService() {
var memory = {};
return {
store: function (key, value) {
memory[key] = value;
},
get: function (key) {
return memory[key];
}
};
}
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" data-semver="1.4.6"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="FirstCtrl" class="firstCtrl">
<h4>{{ctrl}}</h4>
<button ng-click="getTwo()">Get Second Ctrl var</button>
<p>{{resTwo}}</p>
</div>
<div ng-controller="SecondCtrl" class="secondCtrl">
<h4>{{ctrl}}</h4>
<button ng-click="getOne()">Get First Ctrl var</button>
<p>{{resOne}}</p>
</div>
</body>
</html>
/* Put your css in here */
.firstCtrl {
display: block;
background: #f5f4f3;
border-radius: 4px;
padding: 10px;
border: 1px solid #eee;
margin-bottom: 20px;
}
.secondCtrl {
display: block;
background: #f5f4f3;
border-radius: 4px;
padding: 10px;
border: 1px solid #eee;
margin-top: 20px;
}