简体   繁体   English

Angular JS $ http请求?

[英]Angular JS $http request?

I am trying to make a $http request with angular js to get a json object from google maps. 我正在尝试使用angular js发出$http请求,以从Google Maps获取json对象。

$http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city' ] + ',Deutschland' + '&sensor=true').success(function(mapData) {
                        angular.extend($scope, mapData);
    });

I read that I need to "inject" $http first, but I just cant get my head around how that works? 我读到我需要先“注入” $http ,但是我无法理解它是如何工作的? I tried to do something like this: 我试图做这样的事情:

angular.module('wmw', [])
.run(['$scope', '$http', function($scope, $http){
    function getTargetCords(data, $scope, $http) {
        var city = data[ 'city' ];
        return $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city' ] + ',Deutschland' + '&sensor=true').success(function(mapData) {
                    angular.extend($scope, mapData);
        });
    }
}]);

But in this case it is saying "getTargetCords is not defined" when I am trying to use it outside of this. 但是在这种情况下,当我试图在此之外使用它时,它说的是“未定义getTargetCords”。 I tried multiple different solutions and cant get my head around how to get this to work. 我尝试了多种不同的解决方案,但始终无法解决这个问题。

Edit: I think the reason why I need this function is maybe quite confusing, so here is my other code: 编辑:我认为为什么我需要此功能的原因可能很令人困惑,所以这是我的其他代码:

var onSuccess = function(position) {
    currentLat = position.coords.latitude ;
    currentLng = position.coords.longitude;
    var thecoords = [];
    $('#filter-list').empty();
    for(i = 0; i<locations.length;i++){
            thecoords = getTargetCords(locations[i]);
            var distance = calculateDistance(currentLat, currentLng, thecoords[0], thecoords[1]);
            addItemToList(locations[i], distance);
    }   
};

// onError Callback receives a PositionError object
function onError(error) {
    alert('Aktueller Standort konnte nicht berechnet werden');
}

navigator.geolocation.getCurrentPosition(onSuccess, onError);

We have different locations and I need the distance for each location. 我们有不同的位置,我需要每个位置的距离。

Please note: as I didn't quite finish the angular part, the "thecoords[0]", "thecoods[1]" are obviously wrong values right now 请注意:由于我还没有完全完成角度部分,因此“ thecoords [0]”,“ thecoods [1]”现在显然是错误的值

UPDATE 2 更新2

http://pastebin.com/WUuYFAnX http://pastebin.com/WUuYFAnX

When we wish to call AngularJS code from within a legacy app, think of the AngularJS code as being a small application existing within a protected container in your legacy application; 当我们希望从旧版应用程序中调用AngularJS代码时,可以将AngularJS代码看作是存在于旧版应用程序中受保护容器中的小型应用程序。 You cannot make calls to it directly, but you can make remote calls. 您不能直接对其进行呼叫,但是可以进行远程呼叫。

You can use the Id of the HTML element where the Controller resides. 您可以使用Controller所在的HTML元素的ID。 (Not recommended) but you can do the following: (不推荐),但是您可以执行以下操作:

HTML Changes, We need ng-controller and ng-app HTML更改,我们需要ng-controllerng-app

<html ng-app="wmw">
<body ng-controller="MainCtrl" id="MainCtrlId">
   ...
</body>
</html>

Angular Code & Native JS Angular代码和本机JS

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

    app.controller('MainCtrl', function ($scope, $http) {

               $scope.getTargetCords = function (data) {

               $http.get(data).success(function (response) {
                    var responseData = JSON.parse(response);
                    console.log(responseData);
               });
            };
    });



function getCords() {
    var city = activeDest['city'];
    var destUrl = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' + activeDest['street'] + ',' + activeDest['city'] + ',Deutschland' + '&sensor=true';

    var MyAngularScope = angular.element($("#MainCtrlId")).scope();
    //Now call your angular method.
    MyAngularScope.getTargetCords(destUrl);
}

For more details on this technique look at this JSFiddle Example . 有关此技术的更多详细信息, 请参见此JSFiddle示例

It is strongly recommended that you redo the application to work within the Angular Ecosystem instead of doing the above. 强烈建议您重做应用程序以使其在Angular生态系统中工作,而不要执行上述操作。

Here is a simple angular setup, separate Angular Controllers into their on JS files and Import them in your HTML like you would with any other JS file. 这是一个简单的角度设置,将Angular Controllers分离到它们的JS文件中,并像使用其他任何JS文件一样将它们导入HTML

var app = angular.module('wmw', []);
app.controller('YourCtrlName', function ($scope, $http) {

    //Inside your controller you can define your "scope functions".
    $scope.getTargetCords= function(){

          $http.get('urlToGet').success(function(response) {
               var responseData = JSON.parse(response);
               console.log(responseData); 
          });

    };
});

Now in your HTML You can have something like this: 现在,在您的HTML中,您可以具有以下内容:

<div ng-app="wmw">
  <div ng-controller="YourCtrlName">
      <button ng-click="getTargetCords()">GET DATA</button>
  </div>
</div>

You were receiving: 您收到了:

getTargetCords is not defined 未定义getTargetCords

Because you were attempting to access an Angular controller method from outside the Angular Application. 因为您试图从Angular应用程序外部访问Angular控制器方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM