如何获取值并将其放入数组angularjs中



这是我的html:我有一个带有项数组的对象。我需要添加一个带有输入值的新数组。

<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>

这是控制器:

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

当我推送空数组时是可以的,但当我尝试推送ng模型的值时失败了:

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

我错过了什么?

您需要将值存储在对象中,然后将其推送到数组中。

$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);
};

最新更新