2

I'm trying to get data from my form in AngularJS, this all works fine except for the field I did not type anything in. I changed the field from hidden to text, but both do not work, however if you inspect element you can see the correct value in it. Here's my HTML:

 <div ng-controller="postMessageCtrl as Ctrl">
    <form ng-submit="processMessage()">
        <div class="form-group">
            <input type="message" class="form-control" placeholder="Message" ng-model="formData.message">


            a{{data.receiver.id}}a
            <input type="hidden" class="form-control" ng-model="formData.receiver" ng-value="data.receiver.id" />
        </div>
        <button type="submit" class="btn btn-primary btnq-lg btn-block">Verzenden</button>
    </form>
</div>

And here's my controller:

app.controller('postMessageCtrl', function ($scope, $http, $state, localStorageService) {

    $scope.formData = {};
    //$scope.formData = localStorageService.get('userKey');

    $scope.formData = {
        key: localStorageService.get('userKey'),
        message: '',
        receiver: ''
    };

    console.log($scope.formData);
});

The key and message are filled correctly, but the receiver id is not. any suggestions?

5
  • Could you please add the implementation of processMessage()? Commented Dec 8, 2015 at 9:59
  • processmessage is below the console.log(formdata), i quit the code right after the console.log Commented Dec 8, 2015 at 10:01
  • I personally don't see the need to submit with AngularJS, because your data object is always loaded correctly due to two-way binding anyway. Just execute a Save() function on button click. May help you avoid complexity. Commented Dec 8, 2015 at 10:05
  • I'm new to angular....i don't really understand how to do that Commented Dec 8, 2015 at 10:06
  • You can simply use ngInit directive for this, check my answer. Commented Dec 8, 2015 at 10:06

3 Answers 3

2

From the answer AngularJS does not send hidden field value:

You cannot use double binding with hidden field. The solution is to use brackets:

<input type="hidden" name="someData" value="{{data}}" /> {{data}}

See this thread on GitHub: https://github.com/angular/angular.js/pull/2574

Since Angular 1.2, you can use ng-value directive to bind an expression to the value attribute of input. This directive should be used with input radio or checkbox but works well with hidden input.

Here is the solution using ng-value:

<input type="hidden" name="someData" ng-value="data" />

Update:

Another solution could be to directly set the value in $scope.formData rather using the hidden input field when you are initializing it:

$scope.formData = {};
//$scope.formData = localStorageService.get('userKey');

$scope.formData = {
    key: localStorageService.get('userKey'),
    message: '',
    receiver: ''
};

$scope.formData.receiver = $scope.data.receiver.id  // Set the value directly in your `formData` since you are using Angular;
console.log($scope.formData);
Sign up to request clarification or add additional context in comments.

8 Comments

aint i doing exactly what you say here....? im using ng value, cause i already read that post.
But you are using ng-model along with the ng-value. Can you please remove that and try again.
Okay, lets take a step back. How are you populating value in $scope.data.receiver.id?
i just put everything in scope.formdata, the key is filled through localstorageservice, and the message + receiver are filled through the form.
The problem is that this way data will never bind to model which OP needs. Plus ngValue doesn't make sense without ngModel. And even if you add ngModel it will still not work because ngValue is intended for radio buttons and option elements within selectboxes.
|
0

The simple solution is to use ngInit directive:

<input type="hidden" class="form-control" 
    ng-model="formData.receiver" 
    ng-init="formData.receiver = data.receiver.id" />

3 Comments

that leaves me with receiver undefined in the console.log
Where data object comes from?
from this line: <li ng-repeat="message in messages | searchForMessage:searchString" ng-init="data.receiver=messages[0].sender">
0

Avoid submit complexion by just handling things with a function call on a button click, like on this Plunk.

Html:

<div ng-controller="postMessageCtrl as Ctrl">
  <form>
      <div class="form-group">
          <input type="message" class="form-control" placeholder="Message" ng-model="messageInput">
          <button ng-click="Add()">Add</button>
          <p></p>
          <button type="submit" class="btn btn-primary btnq-lg btn-block" ng-click="Send()">Send</button>
      </div>
      <p></p>
      <b>Messages</b>
      <ul>
        <li ng-repeat="message in formData.messages">{{message}}</li>
      </ul>
  </form>
</div>

AngularJS Controller:

app.controller("postMessageCtrl", [
      "$scope",
      "$http",
      function($scope, $http){
        var self = {};

        $scope.messageInput = '';

        $scope.formData = {
            key: 'someUserKey',
            messages: [],
            receiver: null
        };

        $scope.Add = function(){
          console.log($scope.messageInput);
          if($scope.messageInput.length > 0) {
            $scope.formData.messages.push($scope.messageInput);
          }
        };

        $scope.Send = function() {
          console.log($scope.formData);

          $http.post("/somehost/action/", $scope.Person).success(function(data, status) {
            $scope.hello = data;
          });
        };
}]);

The sample will have a 400 bad request error in console, because the url used is obviously not going to work, but the principle is correct.

This way you don't even need to add hidden fields, because they aren't needed (you always have their value from $scope.Person).

Conclusion:

There are 2 things that didn't make sense from your original question:

a{{data.receiver.id}}a

You should use formData here, data isn't defined.

JSON is incorrect

Receiver doesn't contain id, given your sample code, it should be defined like so:

$scope.formData = {
        key: localStorageService.get('userKey'),
        message: '',
        receiver: {
          id: 1,
          name: 'SomeReceiver'
        }
    };

So if your receiver is set like this:

$scope.formData.receiver = $scope.formData.messages[0].receiver;

You will need to implement some way of providing that receiver through messages[0];

You'll notice that the receiver becomes an Object in the console log.

6 Comments

i followed your example 100% now, but now it still shows me the hidden field is empty.
a{{data.receiver.id}}a this var is showing the variable on screen, so i am sure i got the correct id. a{{data.receiver.id}}a <-- is the id i need.
I know, it just won't work because data isn't defined, see my answer.
isnt data defined here? <li ng-repeat="message in messages | searchForMessage:searchString" ng-init="data.receiver=messages[0].sender">
It isn't defined in your controller, given the code you provided. It's just not there.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.