Reputation: 57
I have locally stored a json file, im working with it but i cannot save it, loosing persistance. This code is in my web controller (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).
So, how can i do it?
Thanxs!
Upvotes: 3
Views: 1271
Reputation: 57
thanks yo everybody, finally i save the data in my localstorage using de json file with parse and stringify !
$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 = "";
}
Upvotes: 0
Reputation: 2243
I think, you need to initialize your users variable before calling the http request.
$scope.users = [];
$http.get("users.json")
.then(function(res) {
$scope.users = res.data;
});
Hope it will fix the undefined object issue.
Upvotes: 2
Reputation: 3733
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).
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.
In below code you haven't define $scope.users
which throws error.
// $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 = "";
};
Upvotes: 0