2014-08-30 66 views
0

所以我有一个角度函数,旨在通过使用传入函数的id查找对象数组中的一些基本细节。基本循环和AngularJS中的if语句问题

无论如何,该功能的作品 - 第一次。也就是说,它成功返回契约ID匹配的第一个对象的客户名称。但是,如果有多个匹配的合同/对象,它只会返回第一个名称。

我知道这必须是一个关于循环的基本问题,但似乎无法让它工作!

非常感谢。

下面是函数:

$scope.getCompanyDetailsByContractId = function(contractId) { 

    for (var i = $scope.customers.length - 1; i >= 0; i--) { 

     if ($scope.customers[i].contracts[i].id == contractId) { 
      return $scope.customers[i].name; 
     }; 

    };; 

} 

这里是数据结构:

$scope.customers = [{ 
      id: 1, 
      name: "John Inc", 
      currentContractLength: 12, 
      currentContractValue: 18000, 
      startDate: "09/01/2014", 
      endDate: "09/01/2015", 
      nextRenewalDate: "09/01/2015", 
      mrr: 1500, 
      contracts: [{ 
       id: 234, 
       status: "won", 
       contractNumber: 1, 
       value: 18000, 
       startDate: "09/01/2014", 
       endDate: "09/01/2015", 
       nextRenewalDate: "09/01/2014" 
      }, 
      { 
       id: 235, 
       status: "pending", 
       contractNumber: 2, 
       value: 18000, 
       startDate: "09/01/2015", 
       endDate: "09/01/2016", 
       nextRenewalDate: "09/01/2016" 
      }] 

     }, { 
      id: 2, 
      name: "Peters Company Ltd", 
      currentContractLength: 3, 
      currentContractValue: 15000, 
      startDate: "09/01/2014", 
      endDate: "09/01/2015", 
      nextRenewalDate: "09/01/2015", 
      mrr: 1500, 
      contracts: [{ 
       id: 543654, 
       status: "won", 
       contractNumber: 1, 
       value: 4200, 
       startDate: "09/01/2014", 
       endDate: "09/01/2015", 
       nextRenewalDate: "09/01/2014" 
      }, 
      { 
       id: 54354, 
       status: "pending", 
       contractNumber: 2, 
       value: 18000, 
       startDate: "09/01/2015", 
       endDate: "09/01/2016", 
       nextRenewalDate: "09/01/2016" 
      }] 
     }]; 

回答

1

看来你应该做的2个循环中的所有候选条件的合同看。

通过以下调用你只是在寻找合同与指数i

$scope.customers[i].contracts[i].id == contractId 

也许你应该这样做

for (var i = $scope.customers.length - 1; i >= 0; i--) { 

    for (var j = 0; j < $scope.customers[i].contracts.length; j++) { 
     if ($scope.customers[i].contracts[j].id == contractId) { 
      return $scope.customers[i].name; 
     }; 
    } 


}; 
+0

是的,当场。男人,大脑褪色:)谢谢! – user2656127 2014-08-30 12:23:14

+0

不客气!不要犹豫,如果它可以为你的答案标记为接受:) – 2014-08-30 12:26:24

+0

完成!再次感谢 – user2656127 2014-08-30 12:46:54