How to get the values and put them in array angularjs

Sam Lewis picture Sam Lewis · Mar 26, 2015 · Viewed 16.5k times · Source

Here is my html: I have an object with arrays of items. I need to add a new array with values from inputs.

<div ng-repeat="item in contact.items">
  <label for="Title">Title</label>
  <select id="Title" ng-model="item.title">
    <option ng-selected="title.value === item.title" ng-repeat="title in titles">
      {{ title.title }}
    </option>
  </select>
</div>
<div class="row">
  <label for="Name"> Name</label>
  <input type="text" id="Name" placeholder="Name" ng-model="item.name">
</div>
<div class="row">
  <a ng-click="addItem();">Save Item</a>
</div>

Here is the controller:

$scope.addItem = function() {
  $scope.contact.items.push({
    name: "",
    title:""
  });
  console.log( $scope.contact.items);
};

It is ok when I push the empty array, but it fails when I try pushing the values form the ng-model:

$scope.addItem = function() {
    $scope.contact.items.push({
        name: $scope.item.name,
        title:$scope.item.title
    });
    console.log( $scope.contact.items);
};

What am I missing?

Answer

M.S. picture M.S. · Mar 26, 2015

You need to store the values in an object and then push it to array.

$scope.item = {};
$scope.addItem = function() {
    var newItem = {};
    newItem.name = $scope.item.name;
    newItem.title = $scope.item.title;
    $scope.contact.items.push(newItem);
    console.log($scope.contact.items);
};