[英]How to push a new item into an array of objects using AngularJS?
在我的網站上是通過點創建的用戶列表。 用戶從一個開始,然后如果要添加另一個,則可以單擊“添加”,它應該在數組內部添加一個具有空值的新對象,並且用戶可以輸入一個新值。 用戶可以繼續添加,直到有5個。我該怎么做? 下面是我的代碼。
我想要:
感謝您的任何幫助!
//HTML
<table>
<tr ng-repeat="item in viaPoints">
<td>
<p class="title-icon form-label">VIA LOCATON {{$index + 1}}</p>
<button style="bottom: -3px;" class="transparent position pull-right" ng-click="removeViaPoint($index)">
<img src="images/icons/close-14.png">
</button>
<input class="form" id="drop-off" type="text" value="{{x}}" ng-model="item.val">
</td>
</tr>
</table>
<button class="add" ng-click="addViaPoint()">+ ADD MORE LOCATIONS</button>
<button class="okay okay-full">OKAY</button>
//Angular
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
//Via Point Objects
$scope.viaPoints = [
{val:"Hanoi"}
]
//Push Via Points
$scope.addViaPoint = function () {
$scope.viaPoints.push("val:''");
}
//Remove Via Point
$scope.removeViaPoint = function (x) {
$scope.viaPoints.splice(x, 1);
}
});
通過制造
$scope.addViaPoint = function () {
$scope.viaPoints.push("val:''");
}
僅使您向該數組添加一個字符串。 如果要添加對象,只需編寫
$scope.addViaPoint = function () {
$scope.viaPoints.push({val:''});
}
您現在要添加一個新的對象,其val
設置為''
至於不允許超過5點,您可以在函數上做一個邏輯門,例如:
if ($scope.viaPoints.length === 5) return;
或者,您可以選擇一種更加用戶友好的方式來根據該長度來停用按鈕 ,例如:
<button class="add"
ng-click="addViaPoint()"
ng-disabled="$scope.viaPoints.length === 5">
+ ADD MORE LOCATIONS
</button>
(盡管您應該使用一種更靈活的方法,並使用一個諸如reachedMaxViaPoints()
類的函數)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.