Retrieve information using the $get method in AngularJS

Attempting to use angular js $get to fetch data. It can be done with a simple function like this:

<script>
    $(document).ready(function() {
        $.getJSON('{% url 'ajax-view' %}', function(data) {
            alert(data['revenue']);
        })
    })


</script>


However, having trouble getting it to work in Angular since it's a new challenge for me.



      <script>

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

        app.controller('MainCtrl', function($scope, $http) {
        $http({
        url: '{% url 'ajax-view' %}',
        method: "GET"
        }).then($scope.getdata = function(response) {
        alert(data['revenue']);
        $scope.data = response;
        });
        });
        </script>

For the full Django template, you can visit:

Answer №1

It is important to ensure that the argument provided to the xhr callback methods of $http (such as then, success, error) is a callback function and not just an expression. You can achieve this by following this example:

.then(function(response) {
    alert(response['revenue']);
    $scope.data = response;
});

Additionally, consider using the more concise $http.get(url) syntax instead of the longer version:

$http({'method': 'GET', 'url': url})
.

Answer №2

According to the documentation, callbacks registered by .then() and .success() have different signatures:

.success(function(data, status, headers, config) {})
// This response format is {data:..., status:..., headers:..., config:...}
.then(function(response) {})

Therefore, your code can be written as

$http.get('{% url 'ajax-view' %}').then(function(response) {
    alert(response.data.revenue);
    $scope.data = response.data;
});

Alternatively, you can use

$http.get('{% url 'ajax-view' %}').success(function(data) {
    alert(data.revenue);
    $scope.data = data;
});

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

Angular controller fails to fetch scope variable in subsequent view

I'm currently working on implementing a login feature that directs a validated user to a personalized HTML view that greets them with their name. The initial view is a login page. When the user clicks the "Log In" button, the ng-click function is sup ...

What is the method for altering the state of a single element within a map?

As I delve into learning React, I encountered a persistent issue that has been absorbing my time for several hours now. The problem revolves around mapping an array of product sizes to buttons and controlling the state change of only the last clicked butto ...

The component is converting a controlled text input to become uncontrolled

There's an error warning popping up, saying "A component is changing a controlled input of type text to be uncontrolled." I'm more used to class components, so functional components are new to me. All I did was: First, I set an initial state for ...

Angular pagination with enforced ellipses using Bootstrap

I have encountered an issue with pagination on the Plnkr I created. You can check out the problem here: http://plnkr.co/edit/YQAUCg5vjcgS1BEGB4nY?p=preview. Essentially, I have a large number of pages and I have set the attribute force-ellipses = true to ...

The CSS class names for Next.js have not been defined yet

Just getting started with next js and trying to use css modules for styling my nav component. However, I noticed that the classname I setup for the nav element is not showing up in the rendered DOM. Even though I can see the generated styles by webpack in ...

Data model disruption caused by incorrect migration in Django version 1

Encountered an unusual issue that I came across twice on my system this morning while working with django 1.9.2. Simply put, I made modifications to a model, changing the following: class Sighting(models.Model): caption = models.CharField(max_len ...

Issue: Unable to locate module '/node_modulesprogressbar/package.json'

Currently, I am facing an issue with the generation of a progress bar using Browserify and progressbar.js. When I try to var ProgressBar = require('node_modules/progressbar');, an error pops up saying Error: Cannot find module '/node_modules ...

React: Applying the active class to mapped elements

I have a component that iterates over an array to generate 10 navigation items. I want to implement an onClick method that will add an active class to the clicked item. Are there any best practices using Hooks or the newer React patterns for achieving this ...

Label it as submit ID rather than value or label

Check out this awesome plugin called https://github.com/aehlke/tag-it. It's really cool! Here is the issue I'm facing: <input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true"> Tags:<br ...

Mouse click failing to trigger CSS property update

I am attempting to create an accordion feature. I want the accordion to expand when hovering over the "accordion head," and also show/hide the accordion body when clicking on the "accordion head." I have successfully implemented the show/hide functionalit ...

Is there a way to prevent selection of past dates and future times in a bootstrap DateTimepicker?

I am looking to restrict past dates when selecting a date and disable future times when selecting a time in datetimepicker. Although I have attempted the code below, it has not yielded the desired results. Please refer to this Fiddle link HTML : <d ...

Top tip for implementing toggle functionality with a specified duration in React.js

I am incorporating React into my web application. I understand how to implement the toggle logic - maintaining a boolean value in my state and updating it when I interact with the toggle trigger. However, I am struggling with how to add animation to this ...

Having Trouble with Imported JavaScript File in Astro

Why isn't the js file working in Astro when I try to import or add a source in the Astro file? For example: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script> I am ...

Utilize the keyof operator on a nullable property

Is there a way to utilize keyof in defining function parameters based on an optional field within an Object, while also including a default value? interface test { example?: { choice1: string, choice2: string } } function sample(param: keyof ...

Instantly reveal menu by pressing button

Is there a way to make my mobile menu open immediately upon touching the button? I have used ontouchstart="" in both buttons to create an overlay on the content when the offcanvas menu is visible. This functions well as soon as the user touches either butt ...

Monitoring modifications in the child elements' status

As a newcomer to AngularJS, I am facing a challenge that requires your expertise. I have a table with numerous columns and input fields. My goal is to mark the row as 'edited' whenever a user modifies the value of an input field. Currently, I hav ...

Node.js, sigma.js, and the typescript environment do not have a defined window

When attempting to set up a sigma.js project with node.js in TypeScript, I encountered a reference error after starting the node.js server: ts-node index.ts The problem seems to be located within the sigma\utils\index.js file. <nodejsproject& ...

There seems to be an issue with Three.js: geometry.addEventListener isn't a recognized

I've been experimenting with Threejs to learn more about it, and I encountered an issue sooner than expected. I'm not sure if the problem lies in my code or within the framework itself (though I suspect it's on my end). The goal was to swap ...

What could be the reason for the child event not updating the state in the parent component (Vue)?

I have a component called customize-charts which contains a Vuetify drawer: <template> <v-col> <v-btn style="float: right" class="mr-4 mt-2" small @click="toggleCustomize" v-if="!open">Custom ...

tag-swapping function

I have a specific HTML code paragraph that I am working with: <p id=tag1> html statements before click </p> My goal is to create a function that will split the paragraph into two separate paragraphs like so : <p id=tag1> html statement ...