我有一些简单的数据,我希望从中创建动态ng-model
名称。我知道,如果您有这些名称,您可以将它们的输入值连接在一起并显示它们,如下所示:
<p>{{blah--bleh}}</p>
但是,如果我事先不知道那些ng型号,或者会有多少个?如何动态创建这些名称,然后创建多少名称显示用户输入的值的总和?
如果不清楚我在问什么,here is a fiddle。我想你会看到我想要的东西。
html
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="invoice in invoices">
<input type="number" step="any" placeholder="Enter Amount"
ng-model="invoice.salesOrder" />
</li>
</ul>
<div class="sum"> Total Amount: ${{blah--blah}}
</div><!-- READ ONLY -->
</div>
js
var app = angular.module('angularjs-starter', [])
.controller("MainCtrl",
function($scope) {
$scope.invoices = [
{
"salesOrder": "5"
},
{
"salesOrder": "6"
},
{
"salesOrder": "7"
}
];
});
答案 0 :(得分:0)
制作如下函数:http://jsfiddle.net/d5ug98ke/2/ 这将计算总数并在输入更改时随时更新绑定变量
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="invoice in invoices">
<input type="number" step="any" placeholder="Enter Amount"
ng-model="invoice.salesOrder" ng-change="getSalesTotal()" />
</li>
</ul>
<div class="sum"> Total Amount: ${{sum}}
</div><!-- READ ONLY -->
</div>
var app = angular.module('angularjs-starter', [])
.controller("MainCtrl",
function($scope) {
$scope.sum = 0;
$scope.invoices = [
{
"salesOrder": "5"
},
{
"salesOrder": "6"
},
{
"salesOrder": "7"
}
];
$scope.getSalesTotal = function(){
$scope.sum = 0;
$scope.invoices.forEach(function(invoice){
$scope.sum += parseInt(invoice.salesOrder, 10);
});
};
});