I was looking for a clock on how to update a service value from a nested controller.
My child controller must update the value in the service. And this value should be displayed in the parent controller.
I made jsfiddle to make it more understandable and easy to use
http://jsfiddle.net/jtsmduxw/3/
<body ng-app="MyApp">
<div ng-controller="parentCtrl">
<p>{{username}}</p>
<div ng-controller="childCtrl">
<p>{{username}}</p>
</div>
</div>
</body>
-
var app = angular.module("MyApp", []);
app.service('authenticationSrv', function () {
var user = 'anonymous';
return {
getUser: function () {
return user;
},
setUser: function (value) {
user = value;
}
};
});
app.controller("parentCtrl", function ($scope, authenticationSrv) {
$scope.username = authenticationSrv.getUser();
});
app.controller("childCtrl", function ($scope, authenticationSrv) {
authenticationSrv.setUser('my name');
$scope.username = authenticationSrv.getUser();
});
(I read and tried updating the parent region variable , but I could not get it to work with this service.)
Thanks!
source
share