Angular - sharing data
share data between two controllers,
by Ben Clayton
HTML
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<div ng-app="project">
<div ng-controller="FirstCtrl">
<h2>{{name}}</h2>
<h3>Client {{client.fullname()}}</h3>
<button ng-click="changenm()" >Change name</button><br/>
<button ng-click="changecolor()" >Change Colour</button><br/><br/>
<input style="color:{{thing.color}}" ng-model="thing.x"/>
</div>
<div ng-controller="SecondCtrl">
<h2>{{name}}</h2>
<h3>The other Client {{other_client.forename}}</h3>
<input style="background-color:{{someThing.color}}" ng-model="someThing.x"/> <br/>
<input ng-model="other_client.forename"/>
<ul>
<li ng-repeat="color in colours">
<button ng-click="changecolor(color)">{{ color }}</button>
</li>
</ul>
</div>
</div>
CSS
.myclass { color:red; }
JavaScript
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : {
x : 100,
color:'red'
}
};
});
projectModule.factory('theClientService', function() {
return {
client : {
forename : 'ben',
surname: 'clayton',
fullname:function(){
return this.forename+' '+this.surname;
},
// nice setter for name
changenm_forename:function(v){
this.forename=v
}
}
};
});
function FirstCtrl($scope, theService,theClientService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
$scope.client =theClientService.client;
$scope.changenm=function(){
$scope.client.changenm_forename('Fred');
}
$scope.changecolor=function(){
$scope.thing.color='blue';
}
}
function SecondCtrl($scope, theService,theClientService) {
$scope.someThing = theService.thing;
$scope.name = "Second Controller!";
$scope.other_client =theClientService.client;
$scope.colours = ['red','green','blue'];
$scope.changecolor=function(v){
console.log(v);
$scope.someThing.color=v;
}
}