TUSHAR TUSHAR - 3 months ago 10
AngularJS Question

How to add text box runtime and insert its value to db in angularjs

I want to create Curd app using AngularJS & MVC.

In that I am able to add, update and delete particular data from grid, but there is one task where I am getting stuck.

Here what I need to do is, I should be able to add multiple run time text box on that insert page to take any no of input from user, so I don't know how to do it and how to add those run time added text box values in DB.

It would be much appreciated if you help me on this.

Answer

Try this, Here is the working fiddle

      <div ng-controller="MyCtrl">
    <div class="row" ng-repeat="(key,val) in data">
      <div class="col-md-12">
        <input type="text" ng-model="val.text">
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <button class="btn btn-primary" ng-click="addTextbox()">
          Add Textbox
        </button>
      </div>
      <div class="col-md-12">
        <button class="btn btn-success" ng-click="sendDataToServer()">
          Send Data
        </button>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        Result = {{data}}
      </div>
    </div>
  </div>

Controller's code

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

function MyCtrl($scope,$http) {
    $scope.data = [];

    $scope.addTextbox = function(){
      $scope.data.push({'text':''});
    }

    $scope.sendDataToServer = function(){
       console.log(JSON.stringify($scope.data));
       $http({
          url: 'your_server_url',
          method: "POST",
          data: JSON.stringify($scope.data),
          headers: {
              'Content-Type': undefined
          }
      }).then(function(res) {
          // do stuff on success
      }, function(errorMsg) {
          console.log(errorMsg);
          // showing error
      });
    }
}

Here you will get all textbox's data into $scope.data, Now you can send this data by clicking Send Data button.

Provide the url where you want to submit this data.

Comment if you have any issue.