我是一名Java程序员。我现在正在使用 JavaScript(特别是 Angular.js)开发移动应用程序。
我对这项技术完全陌生,因此我试图弄清楚当从一个 View 切换到共享同一 Controller 的另一个 View 时如何在 Controller 范围内保存值。
例如:这是我的 UserController
.controller('UserCtrl',['$scope','UserService',function($scope, UserService) {
UserService.getAll().success(function(data){
$scope.items=data.results;
});
UserService.get("h7D2wy5lIs").then(function(data){
$scope.item = data.data;
});
$scope.onItemDelete = function (item) {
UserService.delete(item.objectId);
$scope.items.splice($scope.items.indexOf(item),1);
};
}])
此 Controller 在两个不同的 View 之间共享。当我导航时, Controller 每次都会重新加载,并且我只需从 REST 服务获取默认用户项一次,然后将其存储在 Controller 的范围中即可使用它。
如果我修改表单中的项目属性,当我返回时,它会从 REST API 获取值,而不是使用我提供的新值保留状态。
有没有办法只初始化一次 Controller 并通过导航保持其状态?
提前致谢。
最佳答案
最好的方法是使用服务在 Controller 之间共享数据,根据您的情况,更新 UserService:
app.factory('userService', function() {
var items = null;
var defaultItem = null;
return {
getAll: function() {
if (!items) {
//get from REST service and set items
}
return items;
},
getDefaultItem: function(id) {
if (!defaultItem) {
//get from REST service and set defaultItem
}
return defaultItem;
},
...
};
});
另请注意,您可能需要使用 $q 的 promise 处理异步调用。
或者你冷设置了 $rootScope 而不是 $scope,但你要求正确的方法:)
关于javascript - 在 Angular.js 中更改 View 时处理 $scope 状态和值的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27387966/