TechplexEngineer TechplexEngineer - 2 months ago 40
AngularJS Question

Angularjs handling promises without $scope

I've got a factory that creates a SubCon $resource for a restful api.

app.factory("SubCon", function($resource) {
return $resource("http://localhost:8010/api/subcontractors/:id");
})


I've got a controller that uses that service, and directly passes the promise returned by querying the service to an ng-repeat.

//in the controller
$scope.partners = this.SubCon.query();


Here is the repeat in the template:

<tr ng-repeat="partner in partners">
<td>{{partner.id}}</td>
<td>{{partner.name}}</td>
<td>?</td>
<td>?</td>
<td>---</td>
<td>?</td>
</tr>


This works great and outputs what I expect.
So we have a policy against using $scope so I refactored the controller and template like this:

//in the controller
this.getPartners = function() {
return this.SubCon.query();
}


And the template:

<tr ng-repeat="partner in ctrl.getPartners()">
<td>{{partner.id}}</td>
<td>{{partner.name}}</td>
<td>?</td>
<td>?</td>
<td>---</td>
<td>?</td>
</tr>


Now when I run this code using angular 1.5.8 I get a digest error as seen below.

So what am I missing. Why does this work with $scope and not using a method on the controller?

angular.js:13920 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.5.8/$rootScope/infdig?p0=10&p1=%5B%5D
at angular.js:68
at Scope.$digest (angular.js:17562)
at Scope.$apply (angular.js:17790)
at done (angular.js:11831)
at completeRequest (angular.js:12033)
at XMLHttpRequest.requestLoaded (angular.js:11966)(anonymous function) @ angular.js:13920
angular.js:17793 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.5.8/$rootScope/infdig?p0=10&p1=%5B%5D

gyc gyc
Answer

Replace $scope.partners = this.SubCon.query(); by this.partners = this.SubCon.query();

Then you can pass a collection normally to ng-repeat:

<tr ng-repeat="partner in ctrl.partners">
Comments