1

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;
};
5
  • The best way to persist data it's with an API system.. I don't know your case but for example you can use localStorage to persist data into the Browser for a lot of time Commented May 15, 2015 at 14:42
  • It is only out of interest. Well I can with localStorage keeping the data if I switch the pages, isn't it? Commented May 15, 2015 at 14:52
  • oh yes! Try this service github.com/grevory/angular-local-storage.. I use in my project Commented May 15, 2015 at 15:04
  • @gianarb Ok thx. I will try this module. Would this also used in REST API applications or do I needn't the localStorage in REST APIs? Commented May 15, 2015 at 15:24
  • Example.. I use localStorage for user configuration and for save identity after user's login.. I use API to save all my datas.. For example list of persons into the database by API :) Commented May 15, 2015 at 15:37

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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);
}

Comments

0

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

2 Comments

Isn't shared scope considered evil?
That's possible :P. But it's a solution :P. (maybe outdated or ugly, but i don't know anything else right now :/)
0

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.

7 Comments

Thx :) short question. I've often seen it in tutorials. Why does the "this" in a variable? What's the advantages about this approach?
You're welcome :), well, service is being instantiated with new keyword unlike factory (though both of them are singletons), so this keyword will refer to its own instantiated object. There's nothing much of an advantage, it just makes your code more organized (in my opinion).
thx for the info :) only one question. Is it better to create a service for CRUD operations?
yes, very much! It's a good practice to separate logic from CRUD operations.
oh, sorry didn't get what you mean. well, make it as a service.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.