一些应用程序状态信息需要存储在Angular服务中,以便全局访问。
app.value('identity', {});
然后在登录后在我的第一个视图的控制器中。我进行GET api调用,以从服务器端收集应用程序状态信息。在成功回调中,将数据传输到我的全局变量(服务)中。
function successCallback(data) {
identity.username = data.username;
identity.email = data.email;
}
我假设identity
会保存整个应用程序中的数据。但是事实并非如此!在我的其他观点中,我注入identity
了控制器
app.controller('anotherController', ['identity', anotherController];
function anotherController(identity){
// access identity here.
$scope.username=identity.username;
}
我第一次来这种观点。username
在页面上正确显示。但是刷新后,看来identity
再次为null!我们该怎么做才能使价值真正持久?
您将var
身份指向一个角度不知道的新对象,因此它无法将该新值带给另一个控制器。我将回调的响应分配给标识属性:
app.value('identity', { data: null });
...
funciton successCallback(data) {
// here, not overwriting identity, but editing a property
identity.data = data;
}
控制器:
app.controller('anotherController', ['identity', anotherController];
function anotherController($scope, identity){
// add the svc to the scope so you can access its properties later
$scope.identity = identity;
}
html模板:
{{ identity.data | json }}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句