Search code examples
angularjsspringspring-mvcdelete-rowangularjs-http

how to pass the data from angularjs to spring controller


Angular js code

var app = angular.module('myApp', ['ngResource']);
 app.controller('UserController', ['$scope', '$resource', '$http',function($scope,$resource,$http) 
    {
 $scope.deleteRec = function()
         {
            $http({
                method: 'DELETE',
                url: 'delete/:username',
                data: {username: $scope.myform.username},
                headers: {'Content-type': 'application/json;charset=utf-8'}
                }).then(function(response){
                    $scope.Messages = response;
                });
        };      
 }]);
<table border="1" width="50%" height="50%"> 
    <tr><th>user_name</th><th>phone</th><th>email</th><th>delete</th></tr>
     <tr data-ng-repeat="user in usernames">
     <td><span data-ng-bind="user.username"></span></td>
      <td><span data-ng-bind="user.phone"></span></td>
       <td><span data-ng-bind="user.email"></span></td>
        <td><button data-ng-click="deleteRec()">delete</button>
       </tr>   
   </table> 

controller code

@RequestMapping(value="/delete/{username}")
    @ResponseBody
    public String delete(@PathVariable String username) 
    {
        System.out.println("delete1");
        String user=retrievedataservice.delete(username);
        System.out.println("delete2");
        return "delete successfully";
    }

Actually, it username cannot pass from angular js to spring Controller. it error come like this Request processing failed; nested exception is java.lang.NullPointerException Description The server encountered an unexpected condition that prevented it from fulfilling the request.


Solution

  • You should pass username into deleteRec() method. because you are using ng-bind and it is one way data binding.

    <table border="1" width="50%" height="50%"> 
      <tr data-ng-repeat="user in usernames">
        <td><span data-ng-bind="user.username"></span></td>
        <td><button data-ng-click="deleteRec(user.username)">delete</button>
      </tr>   
    </table> 
    

    and

    $scope.deleteRec = function(username)
         {
            $http({
                method: 'DELETE',
                url: 'delete/:username',
                data: {username: username},
                headers: {'Content-type': 'application/json;charset=utf-8'}
                }).then(function(response){
                    $scope.Messages = response;
                });
        };      
    }]);