2014-12-07 203 views
0

我目前處於初學者級別的javascript和angular.js框架。 我的問題是我無法使ngResource工作。請求REST服務

Plunker

我的代碼:

JS:

var geolocationControllers = angular.module('geolocationControllers', ['ngResource']); 

geolocationControllers.controller('geolocationControllers', ['$scope', '$resource', 
    function($scope, $resource) { 

    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position) { 
     $scope.$apply(function() { 
      $scope.position = $resource('http://nominatim.openstreetmap.org/reverse?format=json', {}, { 
      query: { 
       method: 'GET', 
       params: { 
       lat: position.coords.latitude, 
       lon: position.coords.longitude 
       } 
      } 
      }); 
      console.log($scope.position); 
     }); 
     }); 
    } 
    } 
]); 

HTML:

<div class="container" ng-controller="geolocationControllers"> 
    <label for="location">Your location:</label> 
    <input type="text" id="location" size="120" ng-model="position"/> 
</div> 

此輸出到控制檯,並且也是輸入元件:

function Resource(value) {   shallowClearAndCopy(value || {}, this);  } 
+0

你介意提供的是什麼,你現在有一個[plunker(http://plnkr.co/)? – Dom 2014-12-07 19:12:10

+0

我終於找到了一些時間,並添加了砰砰聲:) – Joe 2014-12-13 22:56:38

回答

1

你可以做這樣的事情......這是可行的,我在瀏覽器中測試了它......你將不得不重新命名,你需要的部分...

HTML

<!DOCTYPE HTML> 
<html ng-app="myApp"> 
<head> 
<meta charset="utf-8"> 
<title>untitled</title> 
<script type="text/javascript" src="angular.min.js"></script> 
<script type="text/javascript" src="app.js"></script> 
</head> 

<body ng-controller="myController"> 

    <label for="location">Your location:</label><br> 
    <input type="text" id="location" size="120" ng-model="positionText"/> 

</body> 
</html> 

和JavaScript

var myApp = angular.module('myApp', []); 

myApp.controller('myController', function ($scope, $http) { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function (curPosition) { 
      var curLongi = curPosition.coords.longitude; 
      var curLati = curPosition.coords.latitude; 

      $http.get('http://nominatim.openstreetmap.org/reverse?format=json&lat='+curLati.toString()+'&lon='+curLongi.toString()).success(function (data) { 
        alert(JSON.stringify(data)); 
        $scope.positionText = data.display_name; 
      }); 


     }); 
    } 
}); 
+0

肯定工作的感謝。只是出於好奇的原因,你不知道我的解決方案爲什麼不起作用嗎?因爲我想在很多情況下使用ngResource,也許它簡化了代碼?或者爲什麼創建ngResource? – Joe 2014-12-13 23:01:22

+0

關於ngResource的知識來自於閱讀一些StackOverflow文章...所以我知道的是ngResource是一個RESTful Factory,它也使用我向您展示的$ http提供程序,但使用額外的REST風格的函數,使它更容易與。。。相互作用。如果我理解它的正確性,ngRessource用於管理本地數據持久性,而$ http是針對另一個Web服務的「普通」POST/GET請求。因此,兩者都是通過AJAX在後臺線程上進行webrequest的REST提供者... – 2014-12-14 07:23:06