[英]How can i save a json file with javascript or angularjs?
I have locally stored a json file, im working with it but i cannot save it, loosing persistance. 我在本地存储了一个json文件,我正在使用它,但我无法保存它,失去了持久性。 This code is in my web controller (angularjs) 这段代码在我的web控制器中(angularjs)
$http.get("users.json")
.then(function(res) {
$scope.users = res.data;
});
$scope.addUser = function() {
$scope.users.push({
name: $scope.user
});
$scope.user = "";
}
$scope.removeUser = function() {
$scope.users.pop({
name: $scope.user
});
$scope.user = "";
}
i know that another way is local storage, but i couldn't use it because i cant list every object in my html code (it says i cannot push or pop in a undefiened object). 我知道另一种方式是本地存储,但我无法使用它,因为我无法列出我的HTML代码中的每个对象(它说我无法推送或弹出未定义的对象)。
So, how can i do it? 那么,我该怎么办呢?
Thanxs! Thanxs!
I think, you need to initialize your users variable before calling the http request. 我想,您需要在调用http请求之前初始化您的用户变量。
$scope.users = [];
$http.get("users.json")
.then(function(res) {
$scope.users = res.data;
});
Hope it will fix the undefined object issue. 希望它能解决未定义的对象问题。
I know that another way is local storage, but i couldn't use it because i cant list every object in my html code (it says i cannot push or pop in a undefiened object). 我知道另一种方式是本地存储,但我无法使用它,因为我无法列出我的HTML代码中的每个对象(它说我无法推送或弹出未定义的对象)。
You can use it if you store data properly by checking whether data is available or not and then adding it. 如果通过检查数据是否可用来正确存储数据然后添加数据,则可以使用它。 Other option is if user
data is going to use for different page's or controller then you can use $rootScope . 其他选项是如果user
数据将用于不同的页面或控制器,那么您可以使用$ rootScope 。
In below code you haven't define $scope.users
which throws error. 在下面的代码中,您没有定义抛出错误的$scope.users
。
// $scope.users = []; // Uncomment code if variable is not defined
// $scope.user = ''; // Uncomment code if variable is not defined
$http.get("users.json")
.then(function(res) {
$scope.users = res.data; // Throws error if not defined earlier
});
$scope.addUser = function() {
$scope.users.push({
name: $scope.user // Here $scope.user throws error if not defined earlier
});
$scope.user = "";
};
thanks yo everybody, finally i save the data in my localstorage using de json file with parse and stringify ! 谢谢你们所有人,最后我使用带有parse和stringify的de json文件将数据保存在我的localstorage中!
$scope.addUser = function() {
var jsonData = [];
if (localStorage.getItem("users")) {
jsonData = JSON.parse(localStorage.getItem("users"));
}
jsonData.push ({
name: $scope.user
});
localStorage.setItem("users",JSON.stringify(jsonData));
$scope.users = jsonData;
$scope.user = "";
}
$scope.removeUser = function(user) {
if (localStorage.getItem("users")) {
jsonData = JSON.parse(localStorage.getItem("users"));
}
for (var index in jsonData) {
if (jsonData[index].name === user.name) {
jsonData.splice(index,1);
}
}
localStorage.setItem("users",JSON.stringify(jsonData));
$scope.users = jsonData;
$scope.user = "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.