What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps.

$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 have come across information suggesting that I need to "inject" $http first. However, I am struggling to understand how this process works. I attempted the following:

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);
        });
    }
}]);

However, when trying to use it outside of this context, I receive an error message stating that "getTargetCords is not defined." Despite attempting various solutions, I am unable to grasp how to make this work.

Furthermore, here is additional code explaining why I require this function:

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);

The objective is to obtain the distance of each location from our current position.

Please keep in mind: as I have yet to finalize the angular aspect, the values of "thecoords[0]," and "thecoods[1]" are currently incorrect.

Answer №1

UPDATE 2

http://pastebin.com/WUuYFAnX

Incorporating AngularJS code into a legacy application involves treating the AngularJS code as a self-contained mini-application within a secure container in the existing legacy app. Direct calls to it are not permitted, but remote calls can be made.

To target the HTML element where the Controller is located, you can consider the following method (though not recommended):

Required HTML modifications: Include ng-controller and ng-app

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

Angular Code & Native 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 a detailed demonstration of this technique, refer to this JSFiddle Example.

It is highly advisable to restructure the application to operate within the Angular Ecosystem instead of resorting to the above methods.

A simple Angular setup involves separating Angular Controllers into their respective JS files and importing them in the HTML just like any other JS file.

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

    //You can define the "scope functions" inside your controller.
    $scope.getTargetCords= function(){

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

    };
});

In the HTML, you can implement something similar to this:

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

You encountered the error:

getTargetCords is not defined

This issue arose from attempting to access an Angular controller method from outside the Angular Application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Currently, only the initial button is functional. I am uncertain if it is due to a script issue or if there is a rule that I inadvertently

As a beginner, I am eager to grasp the fundamentals and rules of Javascript. My goal is to create a basic example that involves a box with three buttons. However, I have encountered an issue where only one button seems to be functional despite having dis ...

Encountering an "Error: Invalid string length" while attempting to iterate over the JavaScript object

I am brand new to the world of programming and currently working on developing my very first app. It's a daily expenses tracker that I have been struggling with. The issue I am facing is when a user adds a new item (such as coffee) and an amount, a ne ...

The OrbitControls function is not able to be instantiated as a constructor

I've been working on creating a WebVR environment for the past week using Three.js, but I'm having trouble getting the VR controls to function correctly. Here are some of the things I've tried: 1. Adding packages in my node_modules and imp ...

Tips for validating the input type "password"

Below is the Jquery Script that I am using: $(document).ready(function(){ $("#myForm").validate({ rules: { username: { required:true }, password: { required:true ...

Converting a JavaScript animation into a video through server-side processing: A step-by-step guide

Attempting to tackle a challenging task but willing to give it a shot: Our team is currently working on developing a website that enables users to generate animations using javascript and html. However, our latest client request involves uploading the cre ...

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...

"Discovering the referring page URL in Next.js: A Step-by-Step

On a webpage, I use router.push('destination-url') to redirect users to an external link. I want to determine if the user has navigated back from the redirected page or not. If they arrived from an external link, they should not be allowed to re ...

Is it possible to remove individual items from a FlatList by clicking on them and updating the state?

I have a FlatList displaying items from an array called data. My goal is to remove each item individually by clicking on it, but currently when I click on one item, all items are deleted at once. Any suggestions on how to address this issue? Here's ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

The complete page gets re-rendered when Nuxt child routes are used

When I attempt to utilize child routes, my goal is to maintain specific data on the page while modifying other content. To illustrate this concept, I have created a straightforward example available at this link. After selecting "cat" and increasing the ...

Creating Positioning Magic with HTML Elements

Currently working on an ASP.NET web app that utilizes a Master, with just a GridView at the bottom and a DIV at the top for further development. The goal is to keep the top DIV or header fixed while scrolling, ensuring it remains in place at the top of th ...

Why are traditional Angular dependencies still necessary even when typedefinitions are being used?

I am currently in the process of transitioning my Angular 1.5 project to use TypeScript. The project is compiled with webpack and even though I have included Angular type definitions in my package.json file as shown below, "@types/angular": "~1.5.19", "@t ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

How can an external style sheet be inserted into an iframe?

My website features an editor on one side and an iframe on the other. Currently, anytime HTML code is entered into the editor and a keyup event occurs, the iframe updates automatically. I am looking to add default styling to the code entered in the editor ...

Can orbit controls be tweened in three.js?

When utilizing the TWEEN function within three.js, I have noticed that it is mainly used for tweening objects. Although I can successfully tween the camera's position, I am looking to also tween the orbit control to mimic following a target while the ...

How to make a form in PHP that can be saved?

I have put together a straightforward, yet lengthy HTML form and I am in need of a way for users to save their progress on the form and return to it at a later time (security is not a major concern). However, I am struggling with how to save the form' ...

Steer clear of wrapping ng-repeat in nested indexes for routing purposes

I am currently working on an Angular application that displays data in 3 item columns using Bootstrap. To achieve this layout, I have implemented the following code snippet to group my array of data into sets of 3: examples.success(function(data) { $sc ...

The element event does not trigger an update on the view

I am trying to display the caret position of my editor on a specific place on the website. I have created a directive and service to share variables between the controller and directive. Inside the directive, I have enabled events like "keyup", "mouseup", ...

Unexpected next() error occurred

Currently, I am working on a project using node.js along with express and MongoDB. I have encountered an error that I cannot seem to understand. When I remove the next() function call, everything works perfectly fine. However, when I include next(), it tr ...