gpt4 book ai didi

javascript - 如何通过输入表单将对象数组添加到 html 列表?

转载 作者:行者123 更新时间:2023-11-28 05:39:33 25 4
gpt4 key购买 nike

我想在我的页面中创建动态列表。用户可以将项目从表单添加到列表中。像这样的事情:

w3school example

但我想添加更多输入并将一个对象发送到 Angular 函数。像这样的事情:

<!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() 创建一个副本,然后将复制的对象推送到数组。

关于javascript - 如何通过输入表单将对象数组添加到 html 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39043537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com