AngularJS:总结循环内子数组的值

我试图显示AngularJS的值。现在我想总结所有的值到它的父变量总和。AngularJS:总结循环内子数组的值

我AngularJs数组类似:

{ 

"isInternalInvoice":1,

"name":"Invoices",

"sum":50,

"articles":[

{

"ID":"130.0000917-17.557000506.1",

"betrag_netto":"20",

},

{

"ID":"130.0000917-17.557000581.1",

"betrag_netto":"30"

}

]

}

代码:

<tr ng-repeat="invoice in currentInternalInvoices" > 

<input type="text" ng-model="invoice.betrag_netto" />

</tr>

如果我做出改变文本框它的工作原理:

<input type="text" ng-model="$parent.data.sum" ng-bind="$parent.data.sum" /> 

但我想在循环内输入时总结所有的值。

回答:

只需创建一个求和函数

$scope.getSum = function() { 

return $scope.data.articles.reduce((a, b) => a+Number(b.betrag_netto), 0);

}

有所为输出它

<div>{{getSum()}}</div> 

,它会自动更新它的价值,只要你改变输入框的值。

看到这个plunkr

回答:

更改HTML添加NG-change事件侦听器作为输入字段更新其总结枝条新的价值。

<tr ng-repeat="invoice in currentInternalInvoices" > 

<input type="text" ng-model="invoice.betrag_netto" ng-change="doSum()" />

</tr>

<input type="text" ng-model="data.sum" />

控制器中添加此代码来处理另外的逻辑:

$scope.doSum = function() { 

$scope.data.sum = $scope.data.articles.reduce((a, b) => a+Number(b.betrag_netto), 0);

}

回答:

你可以创建一个自定义指令

(function() {  

"use strict";

class MyController {

constructor(dataService) {

this.dataService = dataService;

this.data = {

sum: 0

}

}

$onInit() {

this.data = this.dataService.get();

console.info('running');

}

static get $inject() {

return ['dataService'];

}

}

const app = angular.module('app', [])

.factory({

dataService

})

.controller({

MyController

})

.directive({

sum

});

function sum() {

return {

restrict: 'A',

bindToController: {

sum: '=',

sumSource: '=',

sumBy: '@',

},

scope: true,

controller: class {

$doCheck() {

this.sum = this.sumSource.reduce((sum, {

[this.sumBy]: value

}) => Number(sum) + Number(value), 0);

}

}

}

}

function dataService() {

return {

get() {

return {

"isInternalInvoice": 1,

"name": "Invoices",

"sum": 50,

"articles": [{

"ID": "130.0000917-17.557000506.1",

"betrag_netto": "20",

},

{

"ID": "130.0000917-17.557000581.1",

"betrag_netto": "30"

}

]

};

}

};

}

}());

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>  

<div ng-app="app" ng-controller="MyController as c">

<table sum="c.data.sum" sum-by="betrag_netto" sum-source="c.data.articles">

<tr ng-repeat="item in c.data.articles">

<td>

<input type="text" ng-model="item.betrag_netto">

</td>

</tr>

</table>

{{c.data | json}}

<div></div>

</div>

以上是 AngularJS:总结循环内子数组的值 的全部内容, 来源链接: utcz.com/qa/265429.html

回到顶部