Share variables between controllers on AngularJS
Hello,
I am going to show you a pretty helpful snippet!
Imagine you have a search bar on your top view and a filterable table on your main content.
How to share the filter value and guarantee a two-way binding? Like this:
var app = angular.module('myApp', []);
app.service('sharedProperties', function() {
var _privateObject = {
data: 'my default value'
};
this.object = _privateObject;
});
app.controller('myController1', function($scope, sharedProperties) {
$scope.object = sharedProperties.object;
});
app.controller('myController2', function($scope, sharedProperties) {
$scope.object = sharedProperties.object;
$scope.object.data = 'my updated value';
});
The value in both controllers will be 'my updated value'
! This also works with inputs and ng-model
directives.
You can find a live demo on this fiddle or a different version here.
Have a good day!