How do I define CRUD operations in a service (AngularJS)

296 views Asked by At

I have a problem with my CRUD operations in the service. When I click on Create Btn it is creating an object but it doesn't push the object in the table list.

Ctrl (where's the table list):

$scope.nameslist = CrudService.getAll();

Ctrl (for Modal dialog):

$scope.createItem = function (newObj) {
   CrudService.create(newObj);
   $scope.newObj = null;
   $scope.ok();
}

CRUD Service (it's a .factory):

...
return {
    getAll: function () {
       return resService.names.query();
    },

    create: function (newObj) {
       resService.names.save(newObj);
       //this.getAll.push(newObj); //this doesn't work
    }
...

Request Service (also a .factory):

...
return {
  names: $resource(baseUrl + '/api/names/:Id', {
      Id: '@Id'
  }, {
     'update': {
          method: 'PUT'
     }
  })
...

Can anyone help me? How can I push the new object in the table list?

1

There are 1 answers

10
Dominic Scanlan On BEST ANSWER

After you've created the object you can push the object to the list or call getAll

$scope.createItem = function (newObj) {
   CrudService.create(newObj);
   $scope.newObj = null;
   $scope.ok();
   \\either
   $scope.nameslist = CrudService.getAll();
   \\or
   $scope.nameslist.push(newObj); // this assumes this is an array
}

UPDATE/// $broadcast sends messages down to child controllers whereas $emit sends them up. using $rootscope.$emit first inject it into the controller

.controller('myCtrl' ['$scope', '$rootscope', function($scope, $rootscope ...

then you can use $rootscope.$emit('added-Name') or you can even add an argument so $rootscope.$emit('added-Name', {newObj: newobj})

then in the catching controller

$rootscope.$on('added-Name'), function(event, args) {
    $scope.namelist.push(args.newObj);
    //or if you're not passing the argument
    $scope.nameslist = CrudService.getAll();
});

using a Shared Service:

angular.module('myApp').service('sharedService', function(){
    var nameList = [];
    return{
        get: function(){
            return nameList;
        }
        set: function(val){
            nameList = val;
        }
        add: function(name){
            nameList.push(name);
        }
    }
})

inject the sharedservice into the controller `.controller('ctrl', ['$scope', 'sharedService', function($scope, sharedService ....

fill the nameList in the service with sharedService.set(CrudService.getAll()); and in $scope.createItem you could have sharedService.add(newObj);

then you can have a watch on the sharedService.get()

$scope.$watch(function() {
            return sharedService.get();
        }, function(newValue, OldValue) {

            if (newValue !== OldValue) {
                $scope.namesList = sharedService.get();
            }
        });