Monday, July 21, 2014

AngularJS : Controller Factory Service Example

The sample below code demonstrate use of factory with controller and how we can share data among controllers.

Html Output

Controller A

{"color":"Seal"}

Seal


Controller B

{"color":"Seal"}

Seal


<html data-ng-app="app" id="ng-app" lang="sv">

<head>

<title>Customer App</title>
</head>

<body>
 

<div data-ng-controller="oControllerA">

<h1>Controller A</h1>

<h2>{{dataObject}}</h2>

<h3>{{dataObject.color}}</h3>

<input type="text" data-ng-model="dataObject.color" />

</div>

<div data-ng-controller="oControllerB">

<h1>Controller B</h1>

<h2>{{dataObject}}</h2>

<h3>{{dataObject.color}}</h3>

<input type="text" data-ng-model="dataObject.color" />

</div>
</body>

</html>

CustomerController.js


var app = angular.module('app', []);

app.factory('ShareService', function () {

return {

dataObject: { color: "Seal" }



}

});
 
app.controller('oControllerA', ['$scope', 'ShareService', function ($scope, ShareService) {



$scope.dataObject = ShareService.dataObject;

}

]);
 
app.controller('oControllerB', ['$scope', 'ShareService', function ($scope, ShareService) {



$scope.dataObject = ShareService.dataObject;

}

]);
 
 

No comments :