Error while retrieving data from local storage - angularjs

i am unable to retreive the data when i reopen my app.What should i do to permanently save the data
I tried this code:
<body ng-app="starter" ng-controller="Appctrl">
<form data-ng-submit="addTodo()" class="todo-form">
<input type="text" data-ng-model="todoText" placeholder="Enter new ToDo
item" />
<br />
<input type="submit" value="Add Task" />
</form>
<ul class="unstyled">
<li data-ng-repeat="item in todo track by $index">
<input type="text">
<span>{{ item.text }}</span>
</li>
</ul>
</body>
and in app.js:
.controller("Appctrl", function($scope) {
$scope.addTodo = function() {
$scope.text = $scope.todoText;
$scope.todos = [];
$scope.todo.push(text);
$scope.todoText = ''; //clear the input after adding
localStorage.setItem('todo', JSON.stringify($scope.todo));
$scope.saved = localStorage.getItem('todo');
localStorage.setItem('todo', JSON.stringify($scope.saved));
};
});

When retrieving the data from local storage check for existence then JSON.parse(localStorage.getItem('todo')) the get from local storage

In your case:
//you will need to parse the string to store it as an object
$scope.saved = JSON.parse(localStorage.getItem('todo'));
You can use the following factory:
yourApp.factory('$localStorage', ['$window', function($window) {
return {
store: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
storeObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key,defaultValue) {
return JSON.parse($window.localStorage[key] || defaultValue);
}
}
}]);
To use the factory you should inject it in your controller and use it like the following:
//to store
$localStorage.storeObject("sometoken", data);
//to retrieve
$localStorage.getObject("sometoken", "");

i solved my issue:
.controller("Appctrl",function($scope){
$scope.saved = localStorage.getItem('id');
$scope.id = JSON.parse($scope.saved);
localStorage.setItem('id', JSON.stringify($scope.id));
$scope.addTodo = function() {
//$scope.text=$scope.todoText;
$scope.id = [];
$scope.id.push({text:$scope.idText});
$scope.idText = ''; //clear the input after adding
localStorage.setItem('id', JSON.stringify($scope.id));
};
});

Check your code in controller.
You are doing : $scope.todo.push(text); instead of $scope.todos.push(text); itseems

Related

Save the value of a service in a variable

I must fill a combo to be able to select the value that the user wanted I have managed to do this with the data stored in an array, the next step is to consult a service and use the return values
<html>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="text">ObjectType:</label>
<input type="text" ng-model="type" ng-keyup="complete(type)" class="form-control" placeholder="Search"/>
<ul class="list-group">
li class="list-group-item" ng-repeat="data in filterType" ng-click="fillTextbox(data)">{{data}}</li>
</ul>
</div>
</div>
</html>
var app = angular.module("Trace", []);
app.controller('TraceControlles', function ($scope, $http) {
//$scope.typeList = ["integration", "none"];
$scope.typeList = [];
$scope.loadTypes = function () {
$http.get("/api/Trace/GetObjectType")
.then(function (responce) {
$scope.typeList = responce.data;
}, function errorCallback(responce) {
});
}
$scope.complete = function (string) {
var output = [];
angular.forEach($scope.typeList, function (type) {
if (type.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(type);
}
});
$scope.filterType = output;
}
$scope.fillTextbox = function (string) {
$scope.type = string;
$scope.filterType = null;
}
});
146/5000
When running the web api the service return values are not loaded, the browser does not mark any syntax error or anything like that.

Sharing data between controllers - Angularjs

i have a problem while im trying to share a data between two controllers.
Here is my code :
<html>
<head>
<title>My Angular App</title>
</head>
<body ng-app="MyTest">
<div ng-controller="ViewController as vmView">
<ul>
<li ng-repeat="singleItem in vmView.allData">
{{ singleItem }}
</li>
</ul>
{{ vmView.checkItOut }}
<input type="button" ng-click="vmView.justClick()" />
</div>
<div ng-controller="AddController as vmAdd">
<form ng-submit="vmAdd.saveChanges()">
<input type="text" ng-model="vmAdd.inputText" />
<input type="submit" />
</form>
</div>
<script src="angular.js"></script>
<script src="app.js"></script>
<script type="application/javascript">
angular.module('MyTest')
.factory('shareDataFactory', function($http, $q) {
var data = {};
data.list = $q.defer();
data.getAllData = function() {
$http.get('http://www.w3schools.com/angular/customers.php')
.then(function(response) {
data.list = $q.resolve(response.data.records);
});
return data.list.promise;
};
data.addData = function(newData) {
data.list.push(newData);
};
return data;
});
angular.module('MyTest')
.controller('ViewController', function ViewController(shareDataFactory) {
var vm = this;
vm.allData = shareDataFactory.getAllData();
vm.checkItOut = "Just checking ..";
vm.justClick = function() {
console.log(vm.allData);
}
});
angular.module('MyTest')
.controller('AddController', function AddController(shareDataFactory) {
var vm = this;
vm.inputText = "Hello";
vm.saveChanges = function() {
shareDataFactory.addData(vm.inputText);
// Clear the data
vm.inputText = "";
};
});
</script>
</body>
</html>
vm.allData its just not updating affter the request come back from the server.
i tried to solve this for a long time but without success.
thanks you everyone and have a lovely week,
rotem
Your code doesn't make much sense:
data.list = $q.defer();
So, data.list is a deferred object. But later
data.list = $q.resolve(response.data.records);
Ah, it's not a deferred anymore: it's being replaced by a resolved promise, unrelated to the promise returned by getAllData(). But later
data.list.push(newData);
Ah, that code thinks it's an array, and not a promise not a deferred.
That can't be right. If you want to be able to push, it must be an array. If you want to populate the array when the http promise is resolved, then push to this aray
It's also unclear what the service should do: it gets data from an HTTP service, but doesn't send the new values to that HTTP service. So, every time you'll call getAllData(), you'll lose the added values.
Anyway:
var list = [];
var getAllData = function() {
$http.get('http://www.w3schools.com/angular/customers.php')
.then(function(response) {
// clear the array
list.splice(0, list.length);
// copy every record to the array
response.data.records.forEach(function(record) {
list.push(record);
});
});
return list;
};
var addData = function(newData) {
list.push(newData);
};
return {
getAllData: getAllData,
addData: addData
};
Here you can find a working version of your code.
When data is loaded, you are replacing the bound list with a new one, so changes aren't getting reflected anymore.
Html
<div ng-controller="ViewController as vmView">
<ul>
<li ng-repeat="singleItem in vmView.allData">
{{ singleItem }}
</li>
</ul>
{{ vmView.checkItOut }}
<input type="button" ng-click="vmView.justClick()" />
</div>
<div ng-controller="AddController as vmAdd">
<form ng-submit="vmAdd.saveChanges()">
<input type="text" ng-model="vmAdd.inputText" />
<input type="submit" />
</form>
</div>
</body>
Javascript
var module = angular.module('MyTest', []);
module.service('shareDataFactory', function($http, $q) {
var data = {
list: []
};
$http.get('http://www.w3schools.com/angular/customers.php')
.then(function(response) {
Array.prototype.push.apply(data.list, response.data.records);
});
return {
getData: function() {
return data;
},
addData: function(newData) {
data.list.push(newData);
}
};
});
module.controller('ViewController', function ViewController($scope, shareDataFactory) {
$scope.allData = shareDataFactory.getData().list;
$scope.checkItOut = "Just checking ..";
$scope.justClick = function() {
console.log($scope.allData);
}
});
module.controller('AddController', function AddController($scope, shareDataFactory) {
$scope.inputText = "Hello";
$scope.saveChanges = function() {
shareDataFactory.addData($scope.inputText);
// Clear the data
$scope.inputText = "";
};
});

how to add an object to list an array in angularjs

I am trying to add an object to the existing list. here is my code.
In controller:
$scope.itemList = [];
$scope.itemList = function () {
return itemService.getItemList();
};
getItemList read from a jason file locally not from service. now I am trying to add new object to this list.
here is my view:
<div>
<img src="/icon1.png" ng-click="sendNewItem()">
<input type="text" ng-model="itemtosend.itemName"/>
<input type="text" ng-model="itemtosend.itemNo"/>
</div>
In controller:
$scope.sendNewItem = function(){
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
$scope.itemList = $scope.itemList.push(newItem)
}
but Iam getting push is not a function. how to add the new object to the existing itemList?
You have many problems in your code :
//You define itemList as an Array (so you can push() in it)
$scope.itemList = [];
//But you redefine it as a function (you cannot push() to a function, ofc..
$scope.itemList = function () {
return itemService.getItemList();
};
then :
$scope.sendNewItem = function(){
//you say newItem is a function, but I guess what you want is an object
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
//$scope.itemList.push(newItem) is enough, no need for list = list.push("b")
$scope.itemList = $scope.itemList.push(newItem)
}
What you should have is :
In controller:
$scope.itemList = [];
$scope.sendNewItem = function(){
var newItem = {
itemName : $scope.itemtosend.itemName,
itenNo : $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
Please find bellow a code snippet :
var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
$scope.itemList = [];
$scope.sendNewItem = function() {
var newItem = {
name: $scope.itemtosend.itemName,
no: $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="Ctrl">
<label>Name :</label><input type="text" ng-model="itemtosend.itemName" />
<label>No :</label><input type="text" ng-model="itemtosend.itemNo" />
<button ng-click="sendNewItem()">Add</button>
<h3>Item List :</h3>
<div ng-repeat="item in itemList">
name : {{item.name}}, num : {{item.no}}
</div>
</div>

Refresh $scope variables from a service

What is the proper method of refreshing data that is retrieved from a service? I am retrieving a test array from my dataService that I'd like to be automatically updated in my view when my save() method is called. I have commented the line that is supposed to update my $scope variable but yet nothing changes. Should I be wrapping it in $apply()?
The data that is placed into the array that dataService.getActivities() returns is from a cookie (which may or not be relevant).
app.controller("activityCtrl", ["$scope", "dataService", function ($scope, dataService) {
$scope.newActivity = "";
$scope.activities = dataService.getActivities();
$scope.save = function (activity) {
try{
if (activity != "") {
dataService.saveActivity(activity);
$scope.newActivity = "";
$scope.activities = dataService.getActivities(); //HERE
}
} catch (e) {
alert(e);
}
}
}
Here is my view, the array lives in a ng-repeat
<div class="col-xs-12" ng-controller="activityCtrl">
<div class="row text-center">
<form novalidate>
<input type="text" placeholder="Activity name" ng-model="newActivity" />
<input type="submit" value="Add activity" ng-click="save(newActivity)" />
</form>
</div>
<div class="row" ng-controller="activityCtrl">
<div class="col-xs-2"> </div>
<div class="col-xs-6 text-left">
<div class="row" ng-repeat="activity in activities">
<div class="btn btn-default" ng-class="{ active : activity.active }" ng-click="activate(activity)">{{ activity.name }}</div>
</div>
</div>
<div class="col-xs-4 text-left">
sdfas
</div>
</div>
</div>
dataService code:
app.service("dataService", function () {
this.getActivities = function () {
if (docCookies.hasItem("activities")) {
var activities = JSON.parse(docCookies.getItem("activities"));
if (activities.constructor != Array) {
activities = [activities];
}
activities.sort(
function (a, b) {
if (a.name > b.name) { return 1; }
if (b.name < a.name) { return -1; }
return 0;
});
return activities;
}
return [];
}
this.saveActivity = function (activity) {
if (!docCookies.hasItem("activities")) {
docCookies.setItem("activities", [JSON.stringify({ "name": activity, "active": true })], Infinity);
} else {
var activities = this.getActivities();
for (var i = 0; i < activities.length; i++) {
if (activities[i].name == activity) {
throw "Activity already exists";
}
}
activities.push({ "name": activity, "active": false });
docCookies.setItem("activities", JSON.stringify(activities), Infinity);
}
};
});
Zac, your answer should work for you. As another option, I like to broadcast an event whenever my service is updated. In the last line of your saveActivity() function in your service, try broadcasting an event on the rootScope. Inject the $rootScope into your service. Add the following to your save method:
$rootScope.$broadcast('activitiesUpdated');
Then in your controller, inject the $rootScope and add an event handler:
$rootScope.$on('activitiesUpdated', function(event, args){
//Update $scope variable here
});
The answer was to look at the cookie value with a call to $watch instead of the method that returns an object. Added this in my activityCtrl
$scope.$watch(function () {
return docCookies.getItem("activities");
}, function (oldVal, newVal) {
$scope.activities = dataService.getActivities();
});

to update in ng-rpeat angularjs

I want to update username in ng-repeat directive. I am able to edit if I take a variable but unable to do so in an array. Here title is a variable and users is an array. I want to update a user's name
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<div ng-hide="editorEnabled">
{{title}} {{name}}
<br>users
<ul> <li ng-repeat="(key,u) in users">
{{key+1}} name: {{u.name}} Edit title
</li></ul>
</div>
<div ng-show="editorEnabled">
<input ng-model="editableTitle" ng-show="editorEnabled"><br><br>
<input ng-model="editableUserName" ng-show="editorEnabled">
Save
or
cancel.
</div>
</div>
</div>
<script>
function ClickToEditCtrl($scope) {
$scope.title = "Welcome to this demo!";
$scope.users = [{'name':'A'},{'name':'B'}];
$scope.editorEnabled = false;
$scope.enableEditor = function(name) {
$scope.editorEnabled = true;
alert(name);
$scope.editableTitle = $scope.title;
$scope.editableUserName = name
};
$scope.disableEditor = function() {
$scope.editorEnabled = false;
};
$scope.save = function() {
$scope.title = $scope.editableTitle;
$scope.users.name = $scope.editableUserName;
$scope.disableEditor();
};
}
</script>`
`
Ideally, you'd like to have an id which doesn't change that associates to each user.
This plunker is your answer plunker
I have gone and used the $index of the array as an id, but ideally you should give each user an id
ng-click="enableEditor($index)"
I have also altered some of your functions to record the index
For the edit pass in the user you are editing:
Edit title
Then store a reference to that user.
var editableUser;
$scope.enableEditor = function(user) {
$scope.editorEnabled = true;
$scope.editableTitle = $scope.title;
$scope.editableUserName = user.name;
editableUser = user;
};
Then in the save, save the changes to the user:
$scope.save = function() {
$scope.title = $scope.editableTitle;
editableUser.name = $scope.editableUserName;
$scope.disableEditor();
};
http://plnkr.co/edit/2VZk2Ej6DR4g51MjiC3j?p=preview

Resources