2

Hello I am developing an Ionic app and I have an array that I want to push items on to it, but not lose the data when I change screens. Also, I do not want to use a database. Is there any other way? to add to an existing array and store that array locally?

 $scope.tasksCollection = [
    { info: 'Go studying', measured: 'no', total: 1, done: 1, id: 1 },
    { info: 'Go to the beach', measured: 'no', total: 1, done: 1, id: 2},
    { info: 'Run', measured: 'yes', total: 30, done: 15, id: 3}
    ];

 $scope.tasksCollection.push({
        info: $scope.taskInfo,
        measured: $scope.result,
        total: total,
        done: 0,
        id: $scope.tasksCollection.length
    })

The add function is working perfectly I just loose the data when changing states.

Joseph Ocasio
  • 989
  • 4
  • 10
  • 19
  • yes, use service. it will be singleton and thus having the same content wherever you inject it. – webduvet May 10 '15 at 15:24
  • possible duplicate of [Ionic local storage vs using service](http://stackoverflow.com/questions/28846266/ionic-local-storage-vs-using-service) – Manish Kr. Shukla May 11 '15 at 04:03

2 Answers2

2

If you want to keep data between controllers either use a service or local storage if you want to keep the data even when you quit the app.

Service example

Further angular documentation regarding services: https://docs.angularjs.org/guide/services

service.js:

angular.module('yourmodule.services')
    .service('Tasks', [function () {
        var collection = {
            tasks: []
        };

        return {
            getTasks : function(){ return collection.tasks; }
        }
    }]
);

controller.js

angular.module('yourmodule.controllers')
    .controller('TaskCtrl', ['$scope', 'Tasks',
        function($scope, Tasks){

   $scope.Tasks = Tasks //Expose service to template

   $scope.addTask = function(){
      Tasks.getTasks().push({name : 'a new task'});
   }
}]);

Local storage example

This is an excellent library which provides easy localstorage access for angularjs: https://github.com/grevory/angular-local-storage

angular.module('yourmodule.controllers')
        .controller('TaskCtrl', ['$scope', 'localStorageService',
            function($scope, localStorageService){

   $scope.collection = {
       tasks : localStorageService.get('tasks') || [];
   }

   $scope.addTask = function(){
      $scope.collection.tasks.push({name : 'a new task'});
      localStorageService.set('tasks', $scope.collection.tasks);
   }
}]);
Rohan
  • 8,006
  • 5
  • 24
  • 32
0

How about HTML5's locaStorage?

See Ionic formulas on Using Local Storage.

chris
  • 1,787
  • 1
  • 13
  • 13