yuro
yuro

Reputation: 2209

Keeping created data in AngularJS

I've a general question about saving data in AngularJS. Are there any opportunities to save data in json files and kept them when you changed the site? I mean when I change the site from "persons" to "home" and go back to "persons" that the created data remain in the list of persons? How can I resolve this? Or is it only possible to do this with a WebApi who is written in Java/C# for example? Does anyone know anything about this?

My example at the current is to push data in the list of json data:

$scope.addItem = function (item) {
  $scope.list.push(item);
  $scope.item = null;
};

Upvotes: 1

Views: 89

Answers (4)

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34217

I can think of 3 ways to get this

create a custom service

You can utilize a dedicated angular service to store and share data between controllers (services are single instance objects)

service definition

 app.service('commonService', function ($http) {

        var info;

        return {
            getInfo: getInfo,
            setInfo: setInfo
        };

        // .................

        function getInfo() {
            return info;
        }

        function setInfo(value) {
            info = value;
        }
});

usage in multiple controllers

app.controller("HomeController", function ($scope, commonService) {

    $scope.setInfo = function(value){
        commonService.setInfo(value);
    };

});


app.controller("PersonsController", function ($scope, commonService) {

    $scope.info = commonService.getInfo();

});

use local storage

You can use the built-in browser local storage and store your data from anywhere

writing

$window.localStorage['my-data'] = 'hello world';

reading

var data = $window.localStorage['my-data']
// ...

via server api

If you need to persist data among different users, you should save it somewhere in the server side (db / cache)

function getProfile() {
    return $http.get(commonService.baseApi + '/api/profile/');
}

function updateProfile(data) {
    var json = angular.toJson(data);
    return $http.post(commonService.baseApi + '/api/profile/', json);
}

Upvotes: 2

Rene Padillo
Rene Padillo

Reputation: 2358

There are many possible ways to do this.

Either you make use of the $rootScope or create a service for holding global variables.

$rootScope sample

// Angular
angular.module('app', [])
       .controller('PersonsController', function ($rootScope) {

            $rootScope.personsList = [
                {
                    name: 'Eve',
                    gender: 'Female'
                },
                {
                    name: 'John',
                    gender: 'Male'
                }
            ];

       })
       .controller('HomeController', function ($rootScope, $scope) {

            // You even don't need to store it in $scope
            // You just use $root.personsList directly in your HTML

       });

// HTML
<div ng-controller="HomeController">
    <ul>
        <li ng-repeat="person in $root.personsList">
            <p>{{ person.name }}</p>
            <p>{{ person.gender }}</p>
        </li>
    </ul>
</div>

Service Sample

// Angular
angular.module('app', [])
       .service('SharedData', function() {

            var sharedData = {};
            var vm = this;
                vm.Set = Set;
                vm.Get = Get;

            /**
             * Set a shared data identified by its key.
             * 
             * @param {String} key - Unique key identifier
             * @param {Any} value - Value to be set
             */
            function Set(key, value) {
                sharedData[key] = value;
            }

            /**
             * Retrieve a shared data.
             * 
             * @param {String} key - The key identifier
             */
            function Get(key) {
                if (sharedData[key])
                    return sharedData[key];
                else
                    return null;
            }

       })
       .controller('PersonsController', function (SharedData) {

            var personsList = [
                {
                    name: 'Eve',
                    gender: 'Female'
                },
                {
                    name: 'John',
                    gender: 'Male'
                }
            ];

            SharedData.Set('personsList', personsList);

       })
       .controller('HomeController', function ($scope, SharedData) {

            $scope.personsList = SharedData.Get('personsList');

       });

// HTML
<div ng-controller="HomeController">
    <ul>
        <li ng-repeat="person in personsList">
            <p>{{ person.name }}</p>
            <p>{{ person.gender }}</p>
        </li>
    </ul>
</div>

I haven't tested the code, but I hope you would get the point between them.

Upvotes: 0

ajliptak
ajliptak

Reputation: 429

It depends on how long you're looking to keep the data around, but there are a few options. If you want to share the data between your app, just while a user is on your website, any of the angular "Services" (Factory, Service, Provider) would work as they are all singletons. For more information on the differences, check out this answer: AngularJS: Service vs provider vs factory

If you are looking to persist data across user visits, you should consider using LocalStorage. There is a great angular local storage module here: https://github.com/grevory/angular-local-storage

Upvotes: 2

Guillaume Munsch
Guillaume Munsch

Reputation: 1283

Dont know if it's what you're looking fort, but un tour controllers you can use the "$rootscope" which is shared between pages (a bit like the session if you want). You can store data in it like in the $scope, and your controller must take the $rootscope in parameter

Upvotes: 0

Related Questions