Iladarsda Iladarsda - 3 months ago 8
AngularJS Question

AngularJS - refresh list after adding new record to collection / db

How do I update/refresh my

$scope.list
when a new record is added to the db/collection -
storage.set()
method - please see comment in the code.

Please see code below.

angular.module("app", [])

.factory('Storage', function() {

var storage = {};
storage.get = function() {
return GetStuffHere();
}
storage.set = function(obj) {
return SetStuffHere(obj);
}
return storage;
})
.controller("MainCtrl", function($scope, Storage) {

$scope.addStuff = function(){

var obj = {
"key1" : "data1",
"key2" : "data2"
};
Storage.set(obj);
// update $scope.list here, after adding new record
}
$scope.list = Storage.get();

});

Answer

Here's an approach that stores the received data in the service as an array. It uses promises within the service to either send the previously stored array (if it exists) or makes an HTTP request and stores the response. Using promise of $http, it returns the newly stored array.

This now allows sharing of the stored array across other controllers or directives. When adding, editing, or deleting, it is now done on the stored array in the service.

app.controller('MainCtrl',function($scope, Storage){
  Storage.get(function(data){
    $scope.items=data
  });

  $scope.addItem=function(){
    Storage.set({name: 'Sue'});
  }
})

app.factory('Storage', function($q,$http) {

    var storage =  {};
    storage.get = function(callback) {
      /* see if already cached */
      if( ! storage.storedData){
        /* if not, get data from sever*/
        return $http.get('data.json').then(function(res){
          /* create the array in Storage that will be shared across app*/
          storage.storedData=res.data;
          /* return local array*/
          return storage.storedData
        }).then(callback)
      }else{
        /* is in cache so return the cached version*/
        var def= $q.defer();
        def.done(callback);
        defer.resolve(storage.storedData);
        return def.promise;
      }


    }
    storage.set = function(obj) {
     /* do ajax update and on success*/
        storage.storedData.push(obj);
    }
    return storage;
})

DEMO

Comments