Problem with array


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:


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


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

2 answers


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:

  var campos = {};
    campos[] = $(this).val();
  var obj = {campos: campos};
<script src=""></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" />
answered by 12.07.2017 в 19:11

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 = [];
      $ = {'data2':'hola1','data3':'hola2'};
      console.log("valor de data" ,$;
        data1 : ((typeof $ === "undefined") ? "" :$, 
        data2 : ((typeof $ === "undefined") ? "" :$, 
        data3 : ((typeof $ === "undefined") ? "" :$
    <script src=""></script>
      <div ng-app="myApp" ng-controller="myCtrl">
        <pre>{{pactUpdates | json}}</pre>
answered by 12.07.2017 в 19:32