Using models in Angular (better and cleaner)
This fiddle shows : instead of listening to change event in every controller, we can inspect the model directly in controller and avoid listeners everywhere.
by Mayank Dixit
HTML
<div ng-controller='mainCtrl'>
<input type='text' ng-model='newData'/>
<button ng-click='setData()'>Set It</button>
<button ng-click='getData()'>Get It</button>
Data is: {{dataSetter.data}}
</div>
<div ng-controller='secCtrl'>
Data is: {{dataSetter.data}}
</div>
JavaScript
angular.module('myApp', []).
service('stepSvc', function($rootScope){
var data = "my name is mayank!!!";
this.data = data;
this.setData = function(reqData){
this.data = reqData;
$rootScope.$broadcast('dataUpdated', data);
}
this.getData = function(){
return this.data;
}
}).
controller('mainCtrl', function($scope, stepSvc){
$scope.dataSetter = stepSvc;
$scope.dataSetter.data = "Mayank Dixit";
$scope.getData = function(){
console.log(stepSvc.getData())
}
$scope.setData = function(){
stepSvc.setData($scope.newData);
}
}).
controller('secCtrl', function($scope, stepSvc){
$scope.dataSetter = stepSvc;
});