Shubham Bhardwaj
Shubham Bhardwaj

Reputation: 155

Store data from these inputs in an array to pass in formdata

HTML part

  <div ng-repeat="tag in tags">
        <input type="text" ng-model="user.tags" />
    </div>

Angular part

$scope.tags = []
    $scope.addTag = function() {
        $scope.tags.push({
    })
}
var info = new FormData();
info.append("tags", $scope.tags);

so i want to store the data from all tag in tags in a single array. I need to pass that array to formData element info

Upvotes: 1

Views: 104

Answers (2)

boy man
boy man

Reputation: 111

Improving on the answer by @HassanImam

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

app.controller("myCtrl", function($scope) {
    $scope.tags = [];
        
    $scope.hisFunction = function() {
      if($scope.x){
         $scope.tags.push($scope.x);
         $scope.x = "";
       }
    }

    $scope.myFunction = function() {
      $scope.tagss="[\"";
      var i=0;
      for(i=0;i<$scope.tags.length;i++){
         $scope.tagss=$scope.tagss+$scope.tags[i];
         if(i<$scope.tags.length-1)
         $scope.tagss=$scope.tagss+"\",\"";
      }
      $scope.tagss=$scope.tagss+"\"]";

      var info = new FormData();
      info.append("tags", $scope.tagss);
      for (var pair of info.entries()) {
         console.log(pair[0]+ ', ' + pair[1]); 
      }
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller="myCtrl">
    <div ng-repeat="tag in tags track by $index">
        <input type="text" ng-model="tag" />
    </div>
        <input type="text" ng-model="x" />
        <button ng-click="hisFunction()">Add</button>
        <button ng-click="myFunction()">Submut</button>
</div>

I know this is not a proper solution, but hey it works.
I hope it helps.

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22574

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

app.controller("myCtrl", function($scope) {
    $scope.tags = [];
        
    $scope.myFunction = function() {
      if($scope.x){
         $scope.tags.push($scope.x);
         $scope.x = "";
       }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller="myCtrl">
    <div ng-repeat="tag in tags track by $index">
        <input type="text" ng-model="tag" />
    </div>
        <input type="text" ng-model="x" />
        <button ng-click="myFunction()">Click Me!</button>
</div>

Upvotes: 2

Related Questions