In this example, we will learn how to share data between AngularJS controllers? A simple solution is to have your factory return an object and let your controllers work with a reference to the same object:
JS Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// declare the app with no dependencies var myApp = angular.module('myApp', []); // Create the factory that share the Fact myApp.factory('Fact', function(){ return { Field: '' }; }); // Two controllers sharing an object that has a string in it myApp.controller('FirstCtrl', function( $scope, Fact ){ $scope.Alpha = Fact; }); myApp.controller('SecondCtrl', function( $scope, Fact ){ $scope.Beta = Fact; }); |
HTML Code:
1 2 3 4 5 6 7 8 9 |
<div ng-controller="FirstCtrl"> <input type="text" ng-model="Alpha.Field"> First {{Alpha.Field}} </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="Beta.Field"> Second {{Beta.Field}} </div> |
Working Demo: http://jsfiddle.net/HEdJF/
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.