I am trying to pass object, controller to another controller using '$sessionStorage'
My first controller, I set the object to the session.
$scope.expandChart = function(obj){
$sessionStorage.chartObject = obj;
$state.go('app.chart-full-view');
}
after i am trying to access this object in another controller. please check below code
Second controller (this is 'chart-full-view' controller)
$scope.test = $sessionStorage.chartObject;
console($scope.test);
when I console my object, console log printed correctly with error. What is this error? I need to correctly access this.
as a solution i tried below way. but did not working
$scope.test = JSON.stringify($sessionStorage.chartObject);
Error is "angular.js:15697 TypeError: Converting circular structure to JSON "
You should use stringify when saving the object in sessionStorage and then use parse when getting it
sessionStorage.setItem("chartObject", JSON.stringify(obj));
As you cannot save objects in sessionstorage only strings.
And then
$scope.test = = JSON.parse(sessionStorage.getItem('chartObject'));
Related
I have a web service that returns an object called response. It has an object data. When I do the following:
var myObject = JSON.stringify(response.data);
console.log("My Results: " + myObject);
[{"id":"1","username":"sam","user_id":"1","status":"1"}]
But I am having trouble accessing these objects in a scope.
for example
$scope.myresponse = response.data;
$scope.myresponse.username = response.data.username
It doesn't work. I even tried $scope.myresponse = response.data[0]; that didnt' work either. Any suggestions?
Store response return from backend call inside a service layer variable and access that variable from controller to get the required result.
Demo code showing above interaction...
In ServiceLayer.js
var myObject = response["data"];
function getMyObject() {
return myObject;
}
In Controller.js
Inject that registered service and access myObject variable.
$scope.myresponse = this.serviceLayer.getMyObject();
use this myResponse variable to access any required information.
Regards
Ajay
Actually the solution turned out be an easy one. Not very clean but it works.
$scope.myData = response.data;
$scope.myResults = $scope.myData[0];
After this I was able to access all the elements e.g. id by {{myResults.id}} in my view.
Thank you all for your help.
I'm having a problem where the cached object doesn't resemble the correct data so I figured it I can push up the most uptodate version to the browser cache it will solve my problem.
How do you update your localStorage with a new object? So if I had a controller with that had an assessment updated. How can I push that assessment object up to the localStorage?
To do that with native JavaScript, you would do something like this:
localStorage.setItem('itemKey', JSON.stringify(yourObject));
var item = JSON.parse(localStorage.getItem('itemKey'));
Within the context of angular, you should make a localStorage service as a wrapper around localStorage and inject it into your service or controller. Or you could inject $window and use it directly off of that like: $window.localStorage
A response specifically for the asker of this duplicate question:
LocalStorage can only store strings, which is why you're stringifying your object before storing it. To manipulate the stored string as an object, you can pass it to JSON.parse (assuming it's properly JSON-formatted). Then to store the modified version, you need to convert it back into a string.
// Creates JSON-formatted object, converts it to a string and stores the string as "ship"
const ship = { name: "black pearl", captain: "Jack Sparrow" };
const originalStringifiedForStorgage = JSON.stringify(ship);
localStorage.setItem("ship", JSON.stringify(ship));
// Retrieves the string and converts it to a JavaScript object
const retrievedString = localStorage.getItem("ship");
const parsedObject = JSON.parse(retrievedString);
// Modifies the object, converts it to a string and replaces the existing `ship` in LocalStorage
parsedObject.name = "newName";
const modifiedndstrigifiedForStorage = JSON.stringify(parsedObject);
localStorage.setItem("ship", strigifiedForStorage);
If the object is in JSON format (not sure if Angular uses a different format) you could probably use the setItem() and getItem() methods to update and retrieve local storage items!
For example taken from the following post:
http://thejackalofjavascript.com/storing-objects-html5-local-storage/
var me = {name:'myname',age:99,gender:'myGender'};
localStorage.setItem("user",me);
//fetch object
console.log(localStorage.getItem("user")); // will return "[object Object]"
You can use full featured Angular module angular-local-storage
An AngularJS module that gives you access to the browsers local
storage with cookie fallback
set
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function submit(key, val) {
return localStorageService.set(key, val);
}
//...
});
get
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function getItem(key) {
return localStorageService.get(key);
}
//...
});
setItem wont work instead it will create another item in localStorage with the same name
Instead directly use
localStorage.item = (what ever the change that you want in the item)
I have looked up several posts with similar issue but was unable to find a solution for my case.
I have a search page that sends a request to the backend an populates the page with search results (each result is an object). I display a concise view of each object and, upon a mouse click on a specific object, the user should be redirected to a page that shows a more detailed view for that object.
On my JS side, I have one controller that handles the $http.post call and retrieves the objects from the backend to display on the first page. I use a different controller for the second page to try and get the relevant object from the first controller (through angular's .service ), but for some reason I get an empty object on the second page. The service works with a getter and a setter. The service is able to set the object just fine, through the first controller, and I am able to print it. However, when redirecting to the second page, while using the second controller's getter, the object gets deleted and shows as empty for some reason.
Here is the relevant code. The service:
app.service('shareService', function(){
var savedData = {}
function set(data) {
savedData = data
console.log(savedData);
}
function get() {
console.log(savedData);
return savedData;
}
return {
set: set,
get: get
}
});
The search (setter) contoller:
app.controller('SearchCtrl', function(shareService, $scope, $http) {
$scope.sendSearch = function() {
$http.post("http://localhost:9080/MedNetApp/rest/mednet/searchCollections", json).success(function (response) {
$scope.collections = response.searchResults;
shareService.set($scope.collections);
});
};
});
The second (getter) controller:
app.controller('CollectionsCtrl', function(shareService, $scope){
$scope.collections = shareService.get();
})
Not sure if this is relevant, but here is also the html part where I set up a temporary test button to redirect to the second page:
<button id=mixing type = "button" class="btn btn-primary-aligned"
data-ng-click = "go('second-page.html')">temp</button>
So, at the end, savedDatashows as empty object when printing it the second time through the get() function. Any idea why this is not working? or a better way to send data to a new page?
EDIT - I should mention that I basically relied on this solution:
AngularJS - Passing data between pages
So, after further research, I came across this solution:
Sharing Data between pages in AngularJS returning empty
I used sessionStorage in my service, as described in the link above, and it fixed the problem.
Use localStorage or sessionStorage
var myJson ={};
localStorage.set("your_Data",myJson);
// to get the value from another page
var returnJson = localStorage.get("Your_Data");
When trying to build a json object from data in $Scope variables, some of the values are not reflected in json.
Below are the details:
1. In my Controller :
$scope.cart.books = [ ];
$scope.cart.date = "";
$scope.cart.pending = "";
var data = {
date: $scope.cart.date,
pending: $scope.cart.pending,
books: $scope.cart.books
};
I am not getting the value of 'date' and 'pending' when I update it in Firebase, but values of 'books' array is correctly updated in Firebase.
But when I log the values of 'date' and 'pending' in console, I am getting the them.
Can someone please suggest where I am going wrong?
Found the solution.
I was using a function in another service to get the values.
It was executing as soon as the code was run and assigning default values in var data.
So I made a new function and only when it is invoked, the values will be filled in var data.
Thank you everyone for your suggestions specially #Patrick Evans and #mak.
I want to post everything that's on angular's scope service, its not much in my case but I don't want to create another object:
var model = angular.toJson($scope);
$http.post('/myUrl', model)
.success(function(data) {
});
However, it looks like $scope is a circular structure, because you can tell via: Converting circular structure to JSON when I use JSON.stringify or the string literal $Scope when I use the sample above.
Is there anyway to capture all of this data off of $scope?
This is my current hack, using underscore and underscore.string:
var toJs = function(item) {
var obj = {};
_.each(item, function(val, key) {
if (!_s.startsWith(key,'$')) {
obj[key] = val;
}
});
return obj;
};
then just passing:
toJs($scope)
You don't want to create new object, so a possible dirty solutions is to remove the circular reference and every other property you don't want to POST from $scope, call toJson, then put all previously deleted properties back to $scope.
Nest a child property on $scope and call toJson on that.
<input ng-model='email'>
becomes
<input ng-model='user.email'>
so that
$http.post('/url', angular.toJson($scope.user));