Jose
Jose

Reputation: 1067

Array is not accessible in angular.forEach

Out of a factory I get data using express and MongoDB with mongoose defined on a model, but I can get the document by the id and have it on the scope but I need to iterate through the array of crews, it works with ng-repeater on the view but I want to pick one subDocument or the array $scope.contractor.crews to send it to a view on from the controller, as the output below shows it is on the $scope.

Here is the Service using $resource

  .factory('Contractors', ['$resource', function($resource){
    return $resource('/contractors/:id', null, {
   'update': { method:'PUT' }
  });
}])

Here is my call to the factory. $scope.contractor = Contractors.get({id: $routeParams.coid });

contractor: f
$promise: Object
$resolved: true
__v: 0
_id: "553569cbbb73900f82b8359a"
active: true
address: "In Delano too"
commission: 30
crews: Array[4]
0: Object
1: Object
2: null
3: null
length: 4
__proto__: Array[0]
fax: "6612953423"
name: "Magbar Contracting"
note: "This one has Mayra maya"
phone: "6613458584"
updated_at: "2015-04-20T21:04:11.681Z"

I have tried with

            $scope.crews = function() {
            var crews = [];
            angular.forEach($scope.contractor.crews, function(crew) {
            crews.push(crew)
            });
            return crews;
        };

        console.log($scope.crews());

but all I get is []

Thanks.

Upvotes: 0

Views: 293

Answers (1)

Miguel
Miguel

Reputation: 20633

Change

$scope.contractor = Contractors.get({id: $routeParams.coid });

To

Contractors.get({id: $routeParams.coid }).then(function(response) {
 $scope.contractor = response;
});

because get returns a Promise object and you get the resolved value from the then callback.

Upvotes: 1

Related Questions