0

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?

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.