$cookie retrieves information in the form of a string rather than a Map

Below is a snippet of my Javascript code.

app.controller('RegisterCtrl', function($scope, $cookies) {

$scope.registerInfo = {};

if($cookies.registerInfo){
angular.forEach($cookies.registerInfo, function(value, key) {
    $scope.registerInfo[key] = value;
});
}

$scope.preserve = function() {
    $cookies.registerInfo = new Map();
    angular.forEach($scope.registerInfo, function(value, key) {
        $cookies.registerInfo.set(key, value);
    });
};

I have already implemented the corresponding HTML which is shown below.

<input type="number" ng-model="registerInfo.lunch_budget_from">
<input type="number" ng-model="registerInfo.lunch_budget_to">
<button ng-click="preserve();">

The issue I am facing is that I intended to store data as a Map on cookies, but '$cookies.registerInfo' seems to be saved as a String instead and I cannot retrieve the values accurately...

Answer №1

When it comes to cookies, they are always in the form of strings and not objects. If you wish to save an object in a cookie, you'll need to serialize and deserialize the object:

app.controller('RegisterCtrl', function($scope, $cookies) {

$scope.registerInfo = {};

if($cookies.registerInfo){
    $scope.registerInfo = JSON.parse($cookies.registerInfo);
}

$scope.preserve = function() {
    var registerInfo = new Map();
    angular.forEach($scope.registerInfo, function(value, key) {
        registerInfo.set(key, value);
    });
    $cookies.registerInfo = JSON.stringify(registerInfo);
};

It's important to note that cookies must not exceed 1K Bytes in length, which includes both name and value. It might be worth considering localStorage as well, as it allows you to store objects without the need for serialization or deserialization.

Before testing this functionality, make sure to delete any existing cookies.

Answer №2

Have you experimented with using the get() method instead of dot notation to retrieve values?

var registerInfo = $cookies.get('registerInfo');

For more information on the $cookies service, check out the following link:

https://docs.angularjs.org/api/ngCookies/service/$cookies

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the concept of 'Abstract classes' within the Svelte framework

As someone who is relatively new to Svelte and frontend development (with primary experience in Rust/C++/Python), I hope you can forgive me for asking what might seem like a basic question. My goal is to showcase different kinds of time-indexed data, with ...

Why does the fillText() method in HTML5 Canvas erase everything after using the clearRect() method?

Whenever I use the writeTextToCanvas method before the clearCanvas method, everything works perfectly. However, if I call the clearCanvas method first and then writeTextToCanvas, the drawing functions work fine after clearing the canvas but the fillText fu ...

Unable to refresh or recreate X-XSRF-TOKEN cookies within the operational environment of my system

These are the software versions I am currently using: Sanctum Version: ^2.14.1 Laravel Version: 9.0 PHP Version: ^8.0.2 Database Driver & Version: Heroku pgql version 14.4 Description I have organized my work into two folders: backend for Laravel Br ...

Tone.js puts an end to all currently playing sounds

With just a button press, I want to play a sequence of notes using a PolySynth and a Sequence. When the button is pressed repeatedly, I want the currently playing notes to stop and restart. The challenge: No matter what method I use, I can't seem to ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Performing AJAX request when a link is clicked within a Wordpress website

I am looking for a way to initiate a PHP function in my Wordpress site when a link is clicked, rather than using a form submission. I have tried using an AJAX request but it doesn't seem to be working. Any suggestions would be greatly appreciated. Be ...

Using VueJS to access dynamic component data within a method executed through v-bind

I am currently facing a unique challenge and finding it difficult to come up with a solution. My project involves creating a file manager-like feature in Vue, where I want specific folders or files to display custom thumbnails. For example, showing the Cr ...

Guide to personalizing the ngxDaterangepickerMd calendaring component

I need to customize the daterangepicker library using ngxDaterangepickerMd in order to separate the start date into its own input field from the end date. This way, I can make individual modifications to either the start date or end date without affectin ...

Route is searching for static files in the incorrect directory

There seems to be a specific route, /admins/:id, that is looking for static files in /public/admins/ instead of /public/. This issue is causing 404 errors and preventing the js and css files from loading on this page. All other routes are correctly fetchin ...

Chrome fails to apply CSS to Polymer 2 web component

The implementation of my web component in Polymer v2 is causing a styling issue specifically in Google Chrome. Despite including a CSS file that defines a style called n-action-button, the styling is not being applied to the content of the web component in ...

Extracting over 100 tweets from the Twitter API with the help of Node.js

I am facing a challenge while trying to fetch over 100 tweets from Twitter in nodejs as I continuously receive an empty array. Here is the approach I have attempted: const MAX_TWEETS = 200; const TWEETS_PER_REQUEST = 100; async function retrieveTweets(T, ...

Transferring information from a form without using specific authorization

Objective: The objective is to display data from a form where users input their name and favorite band. Upon submission, they will be redirected to a new page which will show: Name: John Doe Favorite Band: The Who Challenge: I am unable to utilize the ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

What is the connection between {{result}} and $scope.result within AngularJS?

I comprehend the concept of binding a model to an element. An example would be... <pre ng-model="result">. This connection is established through the $scope.result variable. However, how are these two related? {{result}} $scope.result = data; ...

Configure gulp tasks based on the environment variable NODE_ENV

Is it possible to set up a specific gulp task based on the value of NODE_ENV? For instance, in my package.json file, I currently have: "scripts": { "start": "gulp" } Additionally, I have various gulp tasks defined such as: gulp.task('developm ...

Click event not triggering on inner div element

Can anyone help me with a simple task I'm attempting to do? The ng-click is not functioning as expected. Could there be an issue with divs nested within another div, or am I just too tired to figure this out? Although the specific item affected is not ...

Pass user input values to PHP via AJAX and display the outcome on a designated div

I am currently working on a project where I need to send an input value to a PHP script and display the returned value in a div using AJAX. However, I seem to be struggling with getting it to work properly. Any assistance or suggestions would be greatly ap ...

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...

Is it common to encounter a "no such file or directory" error when running Docker-Compose with the command "ENTRYPOINT ['./init.sh']" in a Dockerfile?

Contemplate the docker-compose configuration : version: '3.0' volumes: data: driver: local networks: simple-network: driver: bridge services: postgres: container_name: postgres image: postgres ...

Can you explain the distinction between the onclick(function(){}) and on('click',function(){}) functions in jQuery?

My goal is to dynamically load pages into a specific div using ajax. Here's my HTML code: <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink">Tab1</a></li> <li><a href="#" id= ...