Problem with array

2

I have a very simple and strange problem in an array in which I declare it for example:

$scope.pactUpdates = [];

The problem is when I push on that array and I want to assign the value of a control that is empty.

$scope.pactUpdates.push({'data1':$scope.data1,'data2':$scope.data2, 'data3':$scope.data3});

The problem is that if in the input data1 do not load anything, in the array I put it in the following way:

{'data2':'hola1','data3':'hola2'}

If I do a second push, it does add the array to me, even though it has not loaded any data with data:

{'data1':'','data2':'hola1111','data3':'hola2222'}

What am I doing wrong? I already try to impute to put a ng-init=' ' to at least take something empty.

    
asked by wagego 12.07.2017 в 18:02
source

2 answers

1

I do not know what happens to the rest of your code.

With the code that follows I want to show that there may be a cleaner and more dynamic way to do what you want.

In the example, you create an array with all the inputs of the form, whether they have data or not. If you are not all interested, you can indicate with a class name or another only those you want.

The object is created using as a key the name tag of each input, and as a value the corresponding value tag:

$(function() 
{
  var campos = {};
  $("#myForm").find(":input").each(function() 
  {
    campos[this.name] = $(this).val();
  });
  var obj = {campos: campos};
  console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <input type="text" name="data0" value="" />
  <input type="text" name="data1" value="hola1" />
  <input type="text" name="data2" value="hola2" />
  <input type="text" name="data3" value="hola3" />
</form>
    
answered by 12.07.2017 в 19:11
0

Your problem is logical, when you create an object in angular with value null will not take it, I propose the following code

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
      $scope.pactUpdates = [];
      $scope.data = {'data2':'hola1','data3':'hola2'};
      console.log("valor de data" ,$scope.data);
      $scope.pactUpdates.push({
        data1 : ((typeof $scope.data.data1 === "undefined") ? "" :$scope.data.data1), 
        data2 : ((typeof $scope.data.data2 === "undefined") ? "" :$scope.data.data2), 
        data3 : ((typeof $scope.data.data3 === "undefined") ? "" :$scope.data.data3)
                        })
      
      
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      <div ng-app="myApp" ng-controller="myCtrl">
        <pre>{{pactUpdates | json}}</pre>
      </div>
    
answered by 12.07.2017 в 19:32