2015-11-03 58 views
0

我想將對象添加到現有列表中。這是我的代碼。 在控制器:如何添加一個對象來列出angularjs中的數組

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

getItemList從賈森文件中讀取本地沒有從服務。現在我正試圖將新對象添加到此列表中。 這裏是我的看法:

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

但蔭越來越推的是不是一個函數。如何將新對象添加到現有的itemList?

回答

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>

相關問題