AngularJS: Factory Shared
by Alberto Naperi Jr.
HTML
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css">
<div ng-controller="FirstCtrl">
<h5>First Controller:</h5>
<div class="clearfix"></div>
<p>Input 1st Ctrl:</p>
<input type="text"
class="form-control"
ng-model="firstControllerInput"
placeholder="First Controller Input" />
<p>From 2nd Ctrl:</p>
<p>{{secondControllerInput}}</p>
</div>
<div class="clearfix"></div>
<div ng-controller="SecondCtrl">
<h5>Second Controller:</h5>
<p>From 1st Ctrl:</p>
<p>{{firstControllerInput}}</p>
<p>Input 2nd Ctrl:</p>
<input type="text"
class="form-control"
ng-model="secondControllerInput"
placeholder="Second Controller Input" />
</div>
JavaScript
'use strict';
var app = angular.module('myApp', []);
app.controller('FirstCtrl', ['$scope', 'sharedDataFactory', function ($scope, sharedDataFactory) {
sharedDataFactory.firstControllerInput = $scope.firstControllerInput;
$scope.secondControllerInput = sharedDataFactory.secondControllerInput;
}]);
app.controller('SecondCtrl', ['$scope', 'sharedDataFactory', function ($scope, sharedDataFactory) {
$scope.firstControllerInput = sharedDataFactory.firstControllerInput;
$scope.secondControllerInput = sharedDataFactory.secondControllerInput;
}]);
app.factory('sharedDataFactory', [function() {
var sharedDataFactory = {
firstControllerInput: '',
secondControllerInput: ''
};
return sharedDataFactory;
}]);