假设我有一个对象,叫做
scope.rec = {a: 2, b: 3, name: a,b};
然后我将“名称”键拆分为 scope.x = scope.rec.name.split(",");
然后 scope.x 将变成一个数组。
现在我需要遍历 View 中的“scope.x”并获取与 scope.rec
上的匹配属性名称关联的值。我只想遍历有效的属性名称,因此我需要在 scope.x
上使用过滤器,但它并没有像我预期的那样工作。
一旦第一部分开始工作,我还需要添加将 scope.rec
属性的值相乘的功能 - 在上面的示例中,它只有 2 个数字(a, b),但也可能超过 2 个。
下面是我试过的代码。
scope.x =
scope.rec.name.split(",");
scope.myFilter = function(y) {
if(!scope.rec.hasOwnProperty(y)) return false;
scope.ys = Number(scope.rec[y]);
return scope.ys;
};
html:
<div ng-repeat="y in x | filter:myFilter">
<label for="{{y}}">{{y}}</label>
<input type="number" id="{{y}}" value={{ys}}>
</div>
<div><input id="calc" type="number" ng-model="calc()" disabled></div>
现在输入中的 ys
对于两个输入都是相同的,并且 calc()
函数无法正确计算值。
提前感谢您的帮助。
最佳答案
您的过滤器(至少您如何在您的 View 中使用它)将收到一个包含所有元素的数组,而不仅仅是一个。所以需要返回一个完整的数组
angular.module('myApp').filter('myFilter', function() {
return function(arrayOfYs, recFromScope) {
var filtered = [];
arrayOfYs.forEach(function(y){
if(!recFromScope.hasOwnProperty(y)) return;
// if the value in the object is already a number, it is not necessary to use Number. If it is not the case, add it
filtered.push(scope.rec[y]);
});
return filtered;
}
});
并返回过滤后的数据。
根据您的看法,您需要使用 Angular 过滤器。
对于你的输入你应该使用这个
<input type="number" id="{{y}}" value={{y}}>
虽然我会删除那个 id - id 需要是唯一的,并且可能有重复的值。
对于您的 calc()
函数,您可以使用 reduce 将它们相乘
$scope.calc = function(){
return $scope.filteredItems.reduce(function(prev, current) {
return prev * current;
}, 1);
};
并获取对 $scope.filteredItems
的引用,在您的 View 中使用它
<div ng-repeat="y in (filteredItems = (x | filter:myFilter:rec))">
关于javascript - ng 在数组上重复以过滤另一个对象上的键以获取关联的值并对该值使用 watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766919/