Javascript AngularJs:在减少计数时从数组中删除元素
我有以下AngularJs代码来根据计数更改项目的数量Javascript AngularJs:在减少计数时从数组中删除元素,javascript,angularjs,Javascript,Angularjs,我有以下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", [], functio
<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>
var app=angular.module(“sub”,[],function(){});
应用程序控制器(“my_ctrl”,函数($scope){
$scope.range=函数(n){
返回新数组(n);
};
$scope.submit=函数(){
log($scope.config);
};
});
项目计数:
项目名称:
当我增加计数并添加新项目时,它就起作用了
但是当我减少计数时,输入框的数量会改变,但是元素不会从items数组中移除
我如何做到这一点 您可以在您的
ng repeat
上使用角度limito
过滤器,该过滤器应能完成您所需的操作
<div ng-repeat="item in config.items track by $index | limitTo: config.no_of_items">
item name: <input name="item" ng-model="item" />
</div>
项目名称:
上述方法可能并不完全有效(我使用Angular 1.x已经有一段时间了),但我会使用它。您可以使用
ng change
重写代码。因此,无论何时更改输入,都将创建与输入的计数对应的相等数量的对象,ng repeat
将在此循环
var-app=angular.module(“sub”,[],function(){});
应用程序控制器(“my_ctrl”,函数($scope){
$scope.range=函数(计数){
$scope.config={
项目:[]
};
对于(变量i=0;i
项目计数:
项目名称:
然后在数字输入上使用“更改侦听器”,并在触发时手动设置数组长度…@Julo0sS,我考虑过,但我需要在很多地方这样做。如果没有简单的替代方法,我会这样做:)谢谢你的回复,但它仍然不会在计数减少时删除元素。所以你想从数组中删除该项,而不仅仅是在视图中隐藏它?然后是-在这种情况下,您需要在config.no\u of_items
输入上设置ng change指令。我在很多地方调用range
函数,因此将数组名称也作为参数传递并尝试。谢谢:)当您减少count的值时,如果您知道应该从哪个索引拼接阵列,则不必重新初始化arry in range函数。您可以从特定索引中剪接数组