角度ng重复未检测到变化

时间:2016-06-01 11:24:26

标签: javascript angularjs

我正在使用ng-repeat通过http.get()迭代json响应。在success()回调中,我运行for循环来创建一个新数组,该数组应由另一个ng-repeat处理。

代码:

$http({
   method: "GET",
   url: "xxx",
   headers: {
    "Accept": "application/json;odata=verbose"
   }
   }).success(function (data, status, headers, config) {

     $scope.onboardings = data.d.results;
     var counter = {};

     for (var i = 0; i < $scope.onboardings.length; i += 1) {
           counter[$scope.onboardings[i].Company] = (counter[$scope.onboardings[i].Company] || 0) + 1;
         }

     $scope.onboardingCompanies = counter;
     console.log($scope.onboardingCompanies);
})

HTML:

<div ng-repeat="item in onboardingCompanies">
    <p>{{item.key}}</p>
    <p>{{item.value}}</p>
</div>

所以我需要ng-repeat来检测$scope.onboardingCompanies中的变化。我知道这里有一些异常的麻烦。

console.log($scope.onboardingCompanies)

Object {Monjasa A/S (FRC): 35, C-bed BV: 2, Monjasa DMCC: 1, Monjasa Pte: 4, Monjasa SA: 9…}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您的HTML错误:Angular没有为您提供具有keyvalue属性的对象,它会分别为您提供:

<div ng-repeat="(key,value) in onboardingCompanies">
    <p>{{key}}</p>
    <p>{{value}}</p>
</div>

您使用的表单ng-repeat="item in onboardingCompanies" angular将尝试迭代数组,但由于该对象不是数组,结果将为空。