39

I have following form:

<form name="frmInput">

    <input type="hidden" ng-model="record.usersId" value="{{user.userId}}"/>
    <input type="hidden" ng-model="record.userNameId" value="{{user.userNameId}}"/>
    <label for="fileNo">AccountId</label>
    <input id="fileNo" ng-model="record.fileNo" required/>
    <label for="madeSad">MadeSad</label>
    <input id="madeSad" ng-model="record.madeSadNo" required/>

    <button ng-disabled="!frmInput.$valid" ng-click="SaveRecord(record)">Accept</button>

</form>

I get record.fileNo and record.madeSadNo in SaveRecord function but i don't get record.usersId and record.userNameId in SaveRecord function.

Where am i making mistake?

values of hidden inputs are correct.

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
MRB
  • 3,752
  • 4
  • 30
  • 44

3 Answers3

43

Having hidden form fields is not the Angular way. You don't need hidden fields at all, as the all the scope variables (which are not in the form) can be taken as hidden variables.

As for the solution, while submitting the form, just populate the object 'record' with 'user':

function SaveRecord(){
  $scope.record.usersId = $scope.user.userId;
  $scope.record.userNameId = $scope.user.userNameId;
  http.post(url, $scope.record);
}

As a side note, you do not need to mention your variable while calling the function:

<button ng-disabled="!frmInput.$valid" ng-click="saveRecord()">Accept</button>
Matt Sach
  • 1,162
  • 16
  • 37
CodingNinja
  • 801
  • 9
  • 17
  • Yes, finally i did that, with similar approach – MRB Nov 28 '13 at 16:28
  • 2
    I don't know if that's an accurate statement.. "hidden variables is not angular way".. what if I have an authorization schema, and depending on the user entering the site, the hidden input is what determines that value? I'd rather not do any authorization in my javascript, but let my view handle it. – sksallaj Jan 11 '16 at 07:14
24

You can use something like this:

<input type="hidden" ng-model="record.usersId" value="{{user.userId}}" ng-init="record.usersId=user.userId"/>
  • 2
    I like this. Of course using hidden fields is not required, as I could just populate directory from the scope....but when one has a page and all other form variables come from form elements...hidden fields helps keep the code clean and consistent – Jim Taliadoros Jul 01 '15 at 09:26
  • 1
    ng-init was key, i wouldn't want to populate the fields in my controller/service as that doesn't help for reusability. In my case, I use a submit function in two places, one where all the data is from the form already, so why make the function ugly? :) – a7omiton Jul 23 '15 at 21:36
2

Hidden field does not support double binding.

Just use this:

<input type="hidden" name="userId" value="{{user.userId}}"/> {{user.userId}}
<input type="hidden" name="UserNameId" value="{{user.userNameId}}"/> {{user.userNameId}}
Bappi Datta
  • 1,360
  • 8
  • 14