Javascript ng在数组上重复以筛选另一个对象上的键,以获取关联的值并对该值使用watch

Javascript ng在数组上重复以筛选另一个对象上的键,以获取关联的值并对该值使用watch,javascript,angularjs,angularjs-directive,angularjs-scope,angularjs-ng-repeat,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,Angularjs Ng Repeat,假设我有一个对象叫做 scope.rec={a:2,b:3,name:a,b} 我将“name”键拆分为scope.x=scope.rec.name.split(“,”)然后scope.x将成为一个数组 现在我需要在视图中迭代“scope.x”,并获取与scope.rec上匹配的属性名称相关联的值。我只想迭代有效的属性名,因此我需要在scope.x上使用一个过滤器,但它没有像我预期的那样工作 一旦第一部分开始工作,我还需要添加功能以将scope.rec属性的值相乘-在上面的示例中,它只有2个数字

假设我有一个对象叫做

scope.rec={a:2,b:3,name:a,b}

我将“name”键拆分为
scope.x=scope.rec.name.split(“,”)然后scope.x将成为一个数组

现在我需要在视图中迭代“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:


{{y}
现在,输入中的
ys
对于两个输入都是相同的,并且
calc()
函数不能正确计算值

提前感谢你的帮助

过滤器(至少在视图中如何使用)将接收包含所有元素的数组,而不仅仅是一个元素。所以您需要返回一个完整的数组

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;
    }
});
并返回过滤后的数据

根据您的观点,您需要使用角度过滤器

对于您的输入,您应该使用此

<input type="number" id="{{y}}" value={{y}}>
要获取对
$scope.filteredItems
的引用,请在视图中使用此选项

<div ng-repeat="y in (filteredItems = (x | filter:myFilter:rec))">

您可以这样做:

angular.module('myApp',[])
.controller(“MyController”,MyController);
函数MyController($scope){
$scope.result=1;
$scope.recObj={};
$scope.rec={
答:2,,
b:3,
c:5,
姓名:“a、b、c、d”
};
函数initData(){
var dataKeysArr=$scope.rec.name.split(“,”);
for(dataKeysArr的var dataKey){
if($scope.rec.hasOwnProperty(dataKey)){
$scope.recObj[dataKey]=$scope.rec[dataKey];
}
}
};
initData();
//监视
$scope.$watchCollection(
“雷科布”,
函数(){
$scope.result=1;
for(var dataKey在$scope.recObj中){
$scope.result*=$scope.recObj[dataKey];
};
}
);
}

{{key}}

calc()的作用是什么?@Gonzalo.-基本上calc()乘以数组的值并返回到“calc”idI我对过滤器接收数组的想法是一样的,但OP使用它的方式实际上只给出单个值。您必须执行
module.filter(“myFilter”,function(){…})
才能获得值数组。您是对的。让我编辑一下。我完全忘记了AO,但视图中的itFilter语法需要更改:
x | myFilter
。您还必须传入
scope.rec
,因为更新的筛选函数中未定义scope。另外,
module.filter()
返回一个函数,该函数执行实际的过滤。应该是这样的:
module.filter(“myFilter”,function(){return function(items){/*do filtering here*/return filteredItems;})
这是我所能得到的,但不断得到无限摘要循环,还有其他我需要得到的东西,所以我放弃了它。完成。我相信现在是正确的回答。我对他的代码和我的代码感到困惑,我也在工作,所以我把所有东西都混在了一起。谢谢你指出我答案中的问题!
$scope.calc = function(){
    return $scope.filteredItems.reduce(function(prev, current) {
         return prev * current;
    }, 1);
};
<div ng-repeat="y in (filteredItems = (x | filter:myFilter:rec))">