TietjeDK TietjeDK - 6 months ago 8
AngularJS Question

Angular ng-repeat not detecting changes

I'm using

ng-repeat
to iterate over a json response via
http.get()
. Inside the
success()
callback i run a for-loop to create a new array which should be handled by another
ng-repeat
.

Code:

$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>


So I need the ng-repeat to detect changes in
$scope.onboardingCompanies
. I know there is some async trouble here.

console.log($scope.onboardingCompanies)
:

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


Any advice?

Answer

Your HTML is wrong: Angular doesn't give you an object with key and value attributes, it gives you them separately:

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

The form you used ng-repeat="item in onboardingCompanies" angular will attempt to iterate over an array, but as the object isn't an array the result will be empty.

Comments