I am trying to pass information from one controller to another using a service.
It works fine, but in the following snippet/Fiddle, I have to:
- type value in input
- click "Set value" button from
FirstController
- click "Get value" button from
SecondController
- The value is now displayed
I want the updated value to be automatically displayed in SecondController
.
angular.module('app', []);
angular.module('app').factory('StoreService', function () {
var storedObject;
return {
set: function (o) {
this.storedObject = o;
},
get: function () {
return this.storedObject;
}
};
});
angular.module('app').controller('FirstController', function ($scope, StoreService) {
$scope.setValue = function (value) {
StoreService.set(value);
};
});
angular.module('app').controller('SecondController', function ($scope, StoreService) {
$scope.getValue = function () {
$scope.value = StoreService.get();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="FirstController">
<fieldset>
<legend>FirstController:</legend>
<input type="text" ng-model="value" />
<button ng-click="setValue(value)">Set value</button>
</fieldset>
</div>
<div ng-controller="SecondController">
<fieldset>
<legend>SecondController:</legend>
<button ng-click="getValue()">Get value</button>
Value: {{value}}
</fieldset>
</div>
</div>