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.

2
  • yes, use service. it will be singleton and thus having the same content wherever you inject it. Commented May 10, 2015 at 15:24
  • possible duplicate of Ionic local storage vs using service Commented May 11, 2015 at 4:03

2 Answers 2

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);
   }
}]);
Sign up to request clarification or add additional context in comments.

Comments

0

How about HTML5's locaStorage?

See Ionic formulas on Using Local Storage.

Comments

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.