【发布时间】:2015-11-19 10:49:30
【问题描述】:
我一直在寻找如何从嵌套控制器更新服务值的几个小时。
我的子控制器需要更新服务中的值。并且该值需要显示在父控制器中。
我制作了一个 jsfiddle 以使其更加清晰和易于帮助 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'); // I need this function to also update the scope of the parent
$scope.username = authenticationSrv.getUser();
});
(我已阅读并尝试过Update parent scope variable,但无法使其与该服务一起使用。)
谢谢!
【问题讨论】:
-
您发布的链接显示基本相同的问题。如果您尝试在那里实施解决方案但失败了,请向我们展示您根据该答案尝试的代码!
标签: javascript angularjs