gpt4 book ai didi

javascript - AngularJs:在减少计数时从数组中删除元素

转载 作者:行者123 更新时间:2023-11-30 21:14:02 25 4
gpt4 key购买 nike

我有以下 AngularJs 代码来根据计数更改项目的数量。

   <head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("sub", [], function() {});
app.controller("my_ctrl", function($scope) {
$scope.range = function(n) {
return new Array(n);
};
$scope.submit = function() {
console.log($scope.config);
};
});
</script>
</head>
<body ng-app="sub" ng-controller="my_ctrl">
<form ng-submit="submit()">
item count:
<input type="number" min="0" max="10" ng-model="config.no_of_items"/>
<div ng-repeat="i in range(config.no_of_items) track by $index">
item name:
<input name="item" ng-model="config.items[$index]"/>
</div>
<input type="submit"></input>
<form>
</body>

当我增加计数并添加新项目时,它会起作用。

但是当我减少计数时,输入框的数量会改变,但元素不会从 items 数组中删除。

我该如何实现?

最佳答案

您可以使用 ng-change 重写您的代码。因此,每当您更改输入时,将创建与输入的计数相对应的相同数量的对象,并且 ng-repeat 将对此进行循环。

var app = angular.module("sub", [], function() {});
app.controller("my_ctrl", function($scope) {
$scope.range = function(count) {
$scope.config = {
items: []
};
for (var i = 0; i < count; i++) {
$scope.config.items.push({});
}
};
$scope.submit = function() {
console.log($scope.config);
};
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>

<body ng-app="sub" ng-controller="my_ctrl">
<form ng-submit="submit()"> item count:
<input type="number" min="0" max="10" ng-model="config.no_of_items" ng-change="range(config.no_of_items)" />
<div ng-repeat="i in config.items track by $index"> item name:
<input name="item" ng-model="i.name" /> </div>
<input type="submit" />
<form>
</body>

关于javascript - AngularJs:在减少计数时从数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862729/

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