Angular和Leaflet:通过promise对象循环并复制其值

时间:2014-11-23 10:40:28

标签: angularjs underscore.js leaflet lodash

在我的控制器中,我有一个在ng-init上执行的功能:

// Find a list of Messages
$scope.find = function() {
    $scope.messages = Messages.query();
};

这是查询()背后的服务:

'use strict';

//Messages service used to communicate Messages REST endpoints
angular.module('messages').factory('Messages', ['$resource',
    function($resource) {
        return $resource('messages/:messageId', { messageId: '@_id'
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

每个消息看起来如何(也就是模型):

0: Resource
  $$hashKey: "00O"
__v: 0
_id: "546fb196971ba6fd20c8db62"
body: "foobar"
created: "2014-11-21T21:41:42.814Z"
location: Object
  lat: 50.827409075117785
  lng: 4.318828582763672

Angular有一个$ scope.markers对象,我们可以在其中推送具有lat和lng属性的标记。

我需要浏览$ scope.messages,获取所有location.lat和location.lng值并将它们放入$ scope.markers._id.lat,$ scope.markers._id.lng ..

我们怎样才能做到这一点?我使用angular.forEach而没有记录任何内容:

// Find a list of Messages
$scope.find = function() {
  $scope.messages = Messages.query();
  console.log($scope.messages);
  angular.forEach($scope.messages, function(i, location) {
    console.log($scope.messages[i]);
  });
};

1 个答案:

答案 0 :(得分:0)

要从查询中访问邮件,您需要执行以下操作:

var messages = Messages.query(function() {
    console.log(messages);
});

如果这正确地将您的消息返回到您的控制台,您的查询就可以了,然后您可以将它们添加到$ scope.markers对象中:

var messages = Messages.query(function() {
    angular.forEach(messages, function(obj, key) {
        $scope.markers[obj._id] = {
            'lat': obj.location.lat,
            'lng': obj.location.lng
        };
    });
});