Angularjs 角度和传单:在promise对象中循环并复制其值
在我的控制器中,我在ng init上执行了一个函数:Angularjs 角度和传单:在promise对象中循环并复制其值,angularjs,underscore.js,leaflet,lodash,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(
// 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'
}
});
}
]);
这就是每个messag在模型中的外观:
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.\u id.lat,$scope.markers.\u 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]);
});
};
要访问查询中的消息,您需要执行以下操作:
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
};
});
});
请检查此答案,谢谢-但是邮件在那里。。它们显示在我的视图中..您是否尝试过Messages.queryfunctionmessages{console.logmessages}?是的,这似乎有效$promise:object,$resolved:True您能告诉我如何使用这种方式在已解析的promise对象中运行forEach吗?