Search code examples
javascriptangularjsrestful-architecture

AngularJS RESTful Web Service - Add row to table without refresh


I'm trying to add a new row to my table after save a new object. The example is as follow:

var demoApp = angular.module("demoApp", ["ngResource"]);

// Controller
demoApp.controller("saveCategoryController", function($scope, saveCategoryService, categoriesService){
    $scope.categories = categoriesService.query();

    $scope.createCategory = function(){
        saveCategoryService.saveCategory($scope.category);
        // I want to avoid this method to refresh my table.
        // $scope.categories = categoriesService.query();

    };    
});

// Factory
demoApp.factory("saveCategoryService", function($resource){
    return $resource("/demopro/saveCategory", {}, {
        saveCategory: {
            method: "POST"
        }
    });
});

demoApp.factory("categoriesService", function($resource){
    return $resource("/demopro/categories", {}, {
        listAllCategories : {
            method: "GET",
            isArray: true
        }
    });
 });

Is there any way to do that without make again a query to my database in order to show the new row in my table?


Solution

  • Yes, logically you would return the saved object on save and add it to the current list:

    $scope.createCategory = function(){
            var newCategory = saveCategoryService.saveCategory($scope.category);
            $scope.categories.push(newCategory);     
    };