我想在我的頁面中創建動態列表。用戶可以從表單中添加項目到列表中。事情是這樣的:如何通過輸入表單將對象數組添加到html列表中?
但我想增加輸入和發送一個對象的角度功能。事情是這樣的:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = [{food: "Milk", price: "1$"}, {food : "Bread", price: "1$"}, {food : "Cheese", price: "1$"}];
$scope.addItem = function() {
$scope.errortext = "";
if (!$scope.addMe) {return;}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
</script>
<div ng-app="myShoppingList" ng-cloak ng-controller="myCtrl" class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{x.food}} : {{x.price}}<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span></li>
</ul>
<div class="w3-container w3-light-grey w3-padding-16">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="addMe.food" class="w3-input w3-border w3-padding">
<input placeholder="Add shopping items here" ng-model="addMe.price" class="w3-input w3-border w3-padding">
</div>
<div class="w3-col s2">
<button ng-click="addItem()" class="w3-btn w3-padding w3-green">Add</button>
</div>
</div>
<p class="w3-padding-left w3-text-red">{{errortext}}</p>
</div>
</div>
</body>
</html>
,但如果我增加了新的項目,以我的列表,然後我開始在文本框變化值也是如此在我的列表中更改值。有像指針這樣的東西。如果我發送字符串數組,然後不這樣做,但我不想連接到一個字符串。現在我已經連接到一個字符串,但我不想要它。
感謝您的所有答案。
使用angular.copy()創建一個副本,然後將該複製的對象推送到數組 – Developer
你能更清楚一點你想要什麼嗎?就像給出一個用戶點擊的例子 - 這意味着發生這種情況,等等 – Cullub
如果你將在文本框輸入並點擊按鈕的東西,然後列表將從文本框中增加新項目的文本。例如,我把這裏鏈接起來。 –