AngularJS Live Example
by johnoscott
HTML
<div ng:app>
<div id="page1" ngm-shared-controller="mod1:Module1Controller">
Mobile Page1:
<input type="text" ng-model="mod1.text" ng-model-instant>
</div>
<div id="page2" ngm-shared-controller="mod1:Module1Controller">
Mobile Page2:
Value: {{mod1.text}}
</div>
</div>
CSS
</style>
<script src="http://docs-next.angularjs.org/angular-1.0.0rc2.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }
body { font-family: Arial,Helvetica,sans-serif; }
body, td, th { font-size: 14px; margin: 0; }
table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }
a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }
.error { color: red; }
JavaScript
Module1Controller = function() {
};
(function(angular) {
var storageName = '$$sharedControllers';
function storage(rootScope) {
return rootScope[storageName] = rootScope[storageName] || {};
}
function sharedCtrl(rootScope, controllerName, $controller, usedInPage) {
var store = storage(rootScope);
var scopeInstance = store[controllerName];
if (!scopeInstance) {
scopeInstance = rootScope.$new();
$controller(controllerName, {$scope: scopeInstance});
store[controllerName] = scopeInstance;
scopeInstance.$$referenceCount = 0;
}
scopeInstance.$$referenceCount++;
usedInPage.bind("$destroy", function() {
scopeInstance.$$referenceCount--;
if (scopeInstance.$$referenceCount===0) {
scopeInstance.$destroy();
delete store[controllerName];
}
});
return scopeInstance;
}
function parseSharedControllersExpression(expression) {
var pattern = /([^\s,:]+)\s*:\s*([^\s,:]+)/g;
var match;
var hasData = false;
var controllers = {};
while (match = pattern.exec(expression)) {
hasData = true;
controllers[match[1]] = match[2];
}
if (!hasData) {
throw "Expression " + expression + " needs to have the syntax <name>:<controller>,...";
}
return controllers;
}
var mod = angular.module('ng');
mod.directive('ngmSharedController', ['$controller', function($controller) {
return {
scope: true,
compile: function(element, attrs) {
var expression = attrs.ngmSharedController;
var controllers = parseSharedControllersExpression(expression);
var preLink = function(scope) {
for (var name in controllers) {
scope[name] = sharedCtrl(scope.$root,...