2015-11-03 90 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>