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;
};
yuro
  • 2,189
  • 6
  • 40
  • 76
  • 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 – GianArb May 15 '15 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? – yuro May 15 '15 at 14:52
  • oh yes! Try this service https://github.com/grevory/angular-local-storage.. I use in my project – GianArb May 15 '15 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? – yuro May 15 '15 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 :) – GianArb May 15 '15 at 15:37

4 Answers4

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

Community
  • 1
  • 1
ajliptak
  • 429
  • 3
  • 7
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);
}
Community
  • 1
  • 1
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
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

Guillaume Munsch
  • 1,233
  • 17
  • 37
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.

Rene Padillo
  • 2,250
  • 4
  • 26
  • 39
  • Thx :) short question. I've often seen it in tutorials. Why does the "this" in a variable? What's the advantages about this approach? – yuro May 15 '15 at 15:08
  • 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). – Rene Padillo May 15 '15 at 15:29
  • thx for the info :) only one question. Is it better to create a service for CRUD operations? – yuro May 15 '15 at 15:32
  • yes, very much! It's a good practice to separate logic from CRUD operations. – Rene Padillo May 15 '15 at 15:35
  • Is it better to create a service or a controller for CRUD? I mean what is recommendable? – yuro May 18 '15 at 07:00
  • 1
    oh, sorry didn't get what you mean. well, make it as a service. – Rene Padillo May 19 '15 at 00:54
  • Can you help me in this thread [here](http://stackoverflow.com/questions/30194123/animate-a-div-box-with-angularjs/) ? – yuro May 19 '15 at 08:45