как добавить объект в список массив в angularjs

0

Я пытаюсь добавить объект в существующий список. вот мой код. В контроллере:

$scope.itemList = [];
 $scope.itemList = function () {
        return itemService.getItemList();
    };

getItemList читается из файла jason локально не из службы. теперь я пытаюсь добавить новый объект в этот список. вот мое мнение:

<div>
<img src="/icon1.png" ng-click="sendNewItem()">
<input type="text" ng-model="itemtosend.itemName"/>
<input type="text" ng-model="itemtosend.itemNo"/>
</div>

В контроллере:

$scope.sendNewItem = function(){
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
  $scope.itemList =   $scope.itemList.push(newItem)
}

но я получаю толчок не является функцией. как добавить новый объект в существующий список элементов?

Теги:

1 ответ

1

У вас много проблем в коде:

//You define itemList as an Array (so you can push() in it)
$scope.itemList = [];
//But you redefine it as a function (you cannot push() to a function, ofc..
$scope.itemList = function () {
   return itemService.getItemList();
 };

тогда:

$scope.sendNewItem = function(){
//you say newItem is a function, but I guess what you want is an object
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
  //$scope.itemList.push(newItem) is enough, no need for list = list.push("b")
  $scope.itemList =   $scope.itemList.push(newItem)
}

То, что вам нужно, это:

В контроллере:

$scope.itemList = [];
$scope.sendNewItem = function(){
  var newItem = {
    itemName : $scope.itemtosend.itemName,
    itenNo : $scope.itemtosend.itemNo
  };
  $scope.itemList.push(newItem)
}

Ниже приведен фрагмент кода:

var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {

  $scope.itemList = [];
  $scope.sendNewItem = function() {
    var newItem = {
      name: $scope.itemtosend.itemName,
      no: $scope.itemtosend.itemNo
    };
    $scope.itemList.push(newItem)
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="Ctrl">
  <label>Name :</label><input type="text" ng-model="itemtosend.itemName" />
  <label>No :</label><input type="text" ng-model="itemtosend.itemNo" />
  <button ng-click="sendNewItem()">Add</button>
  <h3>Item List :</h3>
  <div ng-repeat="item in itemList">
   name : {{item.name}}, num  : {{item.no}}
  </div>
</div>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню