Vikrant
Vikrant

Reputation: 444

Pass hidden values to JSON using AngularJS

Im basic developer , just wanted to pass hidden values from my html page in a json array . Following is my code :-

Index.html

  <!doctype html>
  <html ng-app="plunker" >
   <head>
     <meta charset="utf-8">
   <title>AngularJS Plunker</title>
   <script>document.write('<base href="' + document.location + '" />');
    </script>
   <link rel="stylesheet" href="style.css">
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
   <script src="app.js"></script>
    </head>
    <body>
    <div ng-controller="WorkingCtrl">
    <h1 ng-bind="vm.heading"></h1>   
    <form name="myForm" novalidate>
    <b> Text: </b>
    <input ng-model="form.text" required /><br>
    <button ng-click="submitForm()" bng-disabled="myForm.$invalid">Click Me!</button>
    </form>
    <p ng-bind="showValues"></p>
     </div>
     </body>
     </html>

app.js

    var app = angular.module('myApp');

    app.controller('WorkingCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.form = {};
    $scope.submitForm = function () {
     $scope.showValues = JSON.stringify($scope.form);
    }

  }]);

Now , the value from ng-model="form.text" successfully returns the result as for unhidden input types

       { "text":"What_ever_text" }  

but how to send a defined value in array, consisting of hidden input type like :-

  <input value="99999" type="hidden" ng-model="form.userid" required />

So , wanted desired output like :-

  { "text":"What_ever_text" , "userid":"99999" } 

any solution ? Note :- The input type should be hidden or any other easier method appreciated. Thanks in advance.

Upvotes: 1

Views: 1544

Answers (1)

jad-panda
jad-panda

Reputation: 2547

hidden input fields also works same as normal fields only.

see the below code

  var app = angular.module('myApp', []);

  app.controller('WorkingCtrl', ['$scope', '$http', function ($scope, $http) {

      $scope.form = {
          text: "some test",
          userid: '12312312312'
      };
      $scope.submitForm = function () {
          $scope.showValues = JSON.stringify($scope.form);
      }

  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="WorkingCtrl">
         <h1 ng-bind="vm.heading"></h1> 
        <form name="myForm" ng-submit="submitForm()" novalidate>Text:
            <input ng-model="form.text" required />
            <br/>
            <input type="hidden" ng-model="form.userid" required />
            <button bng-disabled="myForm.$invalid">Click Me!</button>
        </form>
        <p ng-bind="showValues"></p>
    </div>
</div>

Upvotes: 1

Related Questions