我使用AngularJS编写了这个用于添加和删除Textbox的代码,但是我想添加将由用户编写的复选框的值并将其显示在同一页面上,以便我能做什么?
下面的代码将显示1个文本框和3个按钮,如果我点击追加,那么它将在页面上再添加一个文本框,当我点击删除时,它将删除最后一个复选框。
我想添加功能,例如,如果我附加4个复选框,每个复选框我插入一些值作为数字,然后我点击添加按钮然后它将返回我之前插入的值的添加并返回它页。那么我应该在代码中写什么
var app = angular.module('abc', []);
app.controller('myCtrl', function($scope) {
$scope.array=[1];
});

<html ng-app="abc" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-repeat="a in array">
Textbox {{a}} <input type="text" id="{{a}}">
</div>
<button ng-click="array.push(array.length+1)">Append</button>
<button ng-click="array.pop(array.length-1)">Remove</button>
<button>Add</button>
</body>
</html>
&#13;
答案 0 :(得分:0)
您可以在范围中创建calcSum
函数,该函数计算输入值的总和并将总和存储在范围中。然后,您可以使用ng-click
调用该函数。
请注意,我更改了数组以直接包含在文本框中输入的值。这样,您可以直接计算数组的总和,而无需手动循环输入。
var app = angular.module('abc', []);
app.controller('myCtrl', function($scope) {
$scope.array=[0];
$scope.calcSum = function() {
$scope.sum = $scope.array.reduce(function(total, num) {
return total + num;
})
}
});
<html ng-app="abc" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-repeat="a in array track by $index">
Textbox {{$index}} <input type="number" ng-model="array[$index]">
</div>
<button ng-click="array.push(0)">Append</button>
<button ng-click="array.pop(array.length-1)">Remove</button>
<button ng-click="calcSum()">Add</button>
<div>{{sum}}</div>
</body>
</html>