Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

How do I hook up an angularjs web form with a spring mvc REST controller, so that only a small fragment of a page is refreshed (instead of the entire page) when the form is submitted?

In this case, only a string is refreshed in the page instead of refreshing the entire page. Specifically, how do I alter the code below so that the only element on the page that refreshes from the server after form submit is <H1>${person.answer}</H1>.

NOTE: the code below has been edited to adhere to @Cotta's suggestions. I am replacing the original code with @Cotta's suggestions instead of appending because I want this to be easy to read.

index.html is:

<!DOCTYPE html>
<html>
<head>
    <!-- CSS ===================== -->
    <!-- load bootstrap -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> 
    <style>
        body    { padding-top:30px; }
    </style>

    <!-- JS ===================== -->
    <!-- load angular -->
    <script src="http://code.angularjs.org/1.2.6/angular.js"></script> 
    <script src="app.js"></script>
</head>

<!-- apply angular app and controller to our body -->
<body ng-app="validationApp" ng-controller="mainController">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">

    <!-- PAGE HEADER -->
    <div class="page-header"><h1>What is your name?</h1></div>

    <!-- FORM -->
    <!-- pass in the variable if our form is valid or invalid -->
    <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->

        <!-- NAME -->
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" class="form-control" ng-model="name" required>
        </div>

        <!-- SUBMIT BUTTON -->
        <button type="submit" class="btn btn-primary">Submit</button>

    </form>

</div><!-- col-sm-8 -->
</div><!-- /container -->
</body>
</html>
<!-- example from: https://scotch.io/tutorials/angularjs-form-validation -->  

app.js is:

var validationApp = angular.module('validationApp', ['ngResource']);

validationApp.controller('mainController', ['$scope'], '$resource', function($scope, $resource) { 
  // function to submit the form after all validation has occurred            
  $scope.submitForm = function(isValid) {

    // check if form is valid before sending data to the server
    if (isValid) {
        var NameCheck = $resource('/api/namecheck', {});
        var result = NameCheck.get();
        console.log(result.answer);
    }

  };

});

RingRestController.java is:

@RestController
@RequestMapping("/api")
public class RingRestController {

    @RequestMapping(value = "/namecheck", method = RequestMethod.POST)
    public @ResponseBody Person create(@RequestBody Person person) {
        String answer = "";
        if (person.getName().equals("Frodo") || person.getName().equals("frodo")){
            answer = "Frodo, would you please hold onto this ring for me?";
        }
        else {
            answer = "Thank you for telling us your name.";
        }
        person.setTransientAnswer(answer);
        return person;
    }

}  

NOTE: this uses the same core project as the angularjs branch of the spring petclinic sample app (I deleted everything in /src/main/webapp and built up new angularjs within the spring project shell. Thus, it uses the same spring.xml config files, which might be related to a solution. You can read the spring config files by clicking on this link.

share|improve this question
1  
use $http to make ajax request, see docs for particulars – charlietfl 2 days ago
    
@charlietfl google generates a bunch of incomplete answers that do not work out of the box. Or google generates fully featured sample apps way beyond the scope of this question. I just want a simple working solution to this question so that I can build up my own app from pieces that I understand instead of relying on a pre-built app. Are you willing to elaborate about this specific question? – CodeMed 2 days ago
    
as mentioned, start with the docs docs.angularjs.org/api/ng/service/$http There are lots of basic ajax tutorials around. You need to create your data object from your model object and send that to server with $http – charlietfl 2 days ago
    
I read all day long and only ask questions when I hit a dead end. I am hoping that someone can answer this question on the level on which it is asked. Thank you. – CodeMed 2 days ago
    
but it is asked for us to code it for you which is too broad. This isn't a coding service. The $http part is quite simple...and you need a script at server to receive the data the same way you would a form – charlietfl 2 days ago

1 Answer 1

You may solve this by:

  1. Include ngResource in your application

    var validationApp = angular.module('validationApp', ['ngResource']);
    
  2. Inject $resource on your controller

    validationApp.controller('mainController', ['$scope', '$resource', function($scope, $resource) { ... }]);
    
  3. Then you may use $resource to create an object responsible for sending your requests inside submitForm:

    var NameCheck = $resource('http://url-to-service', {});
    var result = NameCheck.get();
    console.log(result.answer);
    
  4. Remember to include angular-resource.js file.

You may also do something similiar with $http and a few lines of code more.

share|improve this answer
    
Thank you for responding. This is Spring MVC, so there is no http://url-to-service. Instead, the REST call would go to /namecheck, as shown in the controller code in my OP. Are you willing to show how your suggestions would fit into the specific code I wrote in my OP? I am currently researching $http, but I am open to your approach if you can show that it works. – CodeMed yesterday
    
All this are changes to your app.js file: #1 and #2 are simple replacements to the first two lines of code (excluding comments), #3 will be placed after the if (isValid) { line and angular-resource.js must be declared on a <script> tag inside your page. – Cotta yesterday
    
I made all of your changes, and then posted them to my OP to replace my previous code. The code does not connect to the server yet. I also added a link to the spring.xml config files at the end of my OP. What else can you suggest? – CodeMed yesterday
    
This link might contain a clue leading to an answer: github.com/singularity-sg/spring-petclinic/blob/master/src/main/… – CodeMed yesterday
    
So this may not be an AngularJS question, but something broader. Did you check if the request is at least being fired by your client side code (eg.: on Google Chrome network tab after hitting F12 key)? – Cotta 5 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.