angular.forEach中无法访问数组

时间:2022-06-01 22:01:47

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.

在工厂外我使用express和MongoDB获取数据,并在模型上定义了mongoose,但是我可以通过id获取文档并将其放在范围上但是我需要遍历一系列的工作人员,它与ng-repeater一起使用在视图上,但我想选择一个subDocument或数组$ scope.contractor.crews将其发送到控制器上的视图,因为下面的输出显示它在$ scope上。

Here is the Service using $resource

这是使用$ 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 });

这是我给工厂的电话。 $ 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.

1 个解决方案

#1


1  

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.

因为get返回一个Promise对象,你从当时的回调中得到解析的值。

#1


1  

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.

因为get返回一个Promise对象,你从当时的回调中得到解析的值。