我的應用程序具有一個具有經度和緯度屬性的Event概念。客戶端,我想使用navigator.geolocation來計算每個事件的當前距離並在視圖中顯示它。在ngResource對象上創建異步「實例方法」
以下是我到目前爲止。它運行,但它陷入了一個無限循環(下面的錯誤)。
factory('ys$currentPosition', ['$q', '$window', function($q, $window){
'use strict';
return {
position: function(){
var deferred = $q.defer();
if ($window.navigator.geolocation) {
$window.navigator.geolocation.getCurrentPosition(
function (position) {
deferred.resolve(position);
},
function (err) {
deferred.reject(err);
}
);
} else {
deferred.reject('Geolocation not supported.');
}
return deferred.promise;
}
};
}]).
factory('Event', ['$resource', 'ys$currentPosition', function($resource, ys$currentPosition){
'use strict';
var Event = $resource($server_hostname + '/api/v4/organizations/' + $org_id + '/events/:id', {}, {});
Event.prototype.distance = function(){
var this_event = this;
return ys$currentPosition.position().then(function(position){
return getDistanceFromLatLonInMi(
position.coords.latitude,
position.coords.longitude,
this_event.latitude,
this_event.longitude
)
});
}
return Event;
}]).
View (in HAML):
%ys-index-row-right{"ng-if" => "item.distance()"}
%i.fa.fa-map-marker
%span
{{ item.distance() }} mi
這裏是一個錯誤:
angular-0195028….js?body=1:69 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"item.distance()","newVal":{},"oldVal":{}}],[{"msg":"item.distance()","newVal":{},"oldVal":"..."}],[{"msg":"item.distance()","newVal":{},"oldVal":"..."}],[{"msg":"item.distance()","newVal":{},"oldVal":"..."}],[{"msg":"item.distance()","newVal":{},"oldVal":"..."}]]
Plunker:
https://plnkr.co/edit/zk5ETxCzvzKYAJOlUPPA?p=preview
其不斷變化.. – amanuel2
創建一個運動員 –
@DrJones plunker補充 - 謝謝! – jsharpe