Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
    
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 – Manish Kr. Shukla May 11 '15 at 4:03

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);
   }
}]);
share|improve this answer

How about HTML5's locaStorage?

See Ionic formulas on Using Local Storage.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.