hanu
hanu

Reputation: 397

how to add an object to list an array in angularjs

I am trying to add an object to the existing list. here is my code. In controller:

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

getItemList read from a jason file locally not from service. now I am trying to add new object to this list. here is my view:

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

In controller:

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

but Iam getting push is not a function. how to add the new object to the existing itemList?

Upvotes: 0

Views: 53

Answers (1)

IggY
IggY

Reputation: 3125

You have many problems in your code :

//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();
 };

then :

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

What you should have is :

In controller:

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

Please find bellow a code snippet :

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>

Upvotes: 1

Related Questions