我正在使用angularjs指令模板从传入的模型中呈现单个计算值(总和)。
如果我使用模板正常渲染值,则没有问题。呈现的值只是传递给指令/模板的一堆行对象值的总和:
ngApp.directive('subtotal', function() {
return {
restrict: 'E',
scope: {
icRows: '='
},
template: '<div><strong>Sub Total:</strong> {{subTotal()}}</div>',
replace: true,
link: function($scope, $element, $attr) {
$scope.subTotal = function() {
var t = 0;
for(var i=0; i<$scope.icRows.length; i++ ) {
t += $scope.icRows[i].price;
}
return t;
}
}
};
});
<div ng-app="app">
<div ng-controller="MyCtrl">
<div ng-repeat="row in rows">
<input ng-model="row.name" /> | <input ng-model="row.price" />
</div>
<hr/>
<subtotal ic-rows="rows"></subtotal>
</div>
</div>
这很好。演示在这里:http : //jsfiddle.net/jralston/p8FLV/
我的问题是'subTotal'变量实际上是AJAX调用的结果。当'rows'变量发生更改时,需要调用此ajax调用。为此,我已将指令中的模板调整为:
<div><strong>Sub Total:</strong> {{subTotalInvoker()}} {{subTotal}}</div>
现在在指令中,函数$ scope.subTotalInvoker()调用ajax调用。从中的回调设置'subTotal'的值
同样,这完全正常。
演示在这里:http : //jsfiddle.net/jralston/wpYjL/
但是,这似乎是完全错误的方法。
我试图在$ scope.icRows中添加一个$ watch,但是没有用。也许我做错了。
非常欢迎您提供任何有关如何最好地做到这一点的指示和/或更正。
谢谢
约翰
您可以使用$ watchCollection。当在范围内替换整个数组(即$ scope.icRows = []),从icRows中添加或删除某项或替换其中一项时,$ watchCollection将调用其监视处理程序。
ngApp.directive('subtotal', function() {
return {
restrict: 'E',
scope: {
icRows: '='
},
template: '<div><strong>Sub Total:</strong> {{subTotal}}</div>',
replace: true,
link: function($scope, $element, $attr) {
$scope.subTotal = 0;
$scope.$watchCollection('icRows', function(newVal) {
var t = 0;
for(var i=0; i<newVal.length; i++ ) {
t += newVal[i].price;
}
$scope.subTotal = t;
}
}
};
});
但是我怀疑这不合适,因为'.price'可能会更改,并且$ watchCollection不会检查项目属性的更改。
如果您需要深入了解(也搜索属性和子属性的更改),请使用$ watch并将true作为第二个参数传递:
$scope.$watch('icRows', function(newVal) {
...
}, true);
$ watch(true)有一些细微之处,您需要注意。我不确定在最近对Angular的更新中是否已更改,但是回到我使用它时,我发现$ watch(true)不会检查数组中的添加/删除,甚至不检查数组是否被完全替换。它确实做得很深入。
过滤器的工作原理类似于$ watchCollection。缺点是,当商品的.price属性更改时,筛选器不会更新。
ngApp.filter('subtotal', function() {
return function(input) {
var t = 0;
for (var i= 0; i < input.length; ++i) {
t += parseFloat(input[i].price);
}
return t;
}
});
然后,在HTML中,可以将过滤器应用于作用域内的数组:
<div ng-app="app">
<div ng-controller="MyCtrl">
<div ng-repeat="row in rows">
<input ng-model="row.name" /> | <input ng-model="row.price" />
</div>
<hr/>
{{ rows | subtotal | currency }}
</div>
</div>
如果这符合您的要求,则无需自定义指令,您可以使用货币过滤器将结果进一步格式化为货币。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句