Assigning controller variables within an ajax request

I'm new to AngularJS and I have a question about controller attributes. I've created an attribute called 'anuncio', which contains an array of objects as shown below:

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

anuncioModule.controller('RegistrationController',['$http',function ($http){

    this.anuncios;

    this.loadAnuncios = function loadAnuncios(){

         $http.get('http://localhost:8080/pederofer/anuncios/get.action').then(function(result){

             this.anuncios.push.apply(this.anuncios, result.data);
        });

    }

}]);

When I call my web service with the function loadAnuncios and try to set the values directly using "this.anuncios", I receive the message "this.anuncios is undefined". But if I create a variable called 'anuncs' and set "this.anuncios = anucs", and instead of setting my AJAX call directly into this.anuncios, I set it to anucs like in the code snippet below, it works.

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

anuncioModule.controller('RegistrationController',['$http',function ($http){

    this.anuncios = anuncs;

    this.loadAnuncios = function loadAnuncios(){

         $http.get('http://localhost:8080/pederofer/anuncios/get.action').then(function(result){

             anuncs.push.apply(anuncs, result.data);
        });

    }

}

My question is, why does this method work?

Answer №1

Perhaps considering approaching your task from a different angle could be beneficial.

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

adModule.controller('RegistrationController', ['$scope', '$http', function ($scope, $http) {
    $scope.ads = [];
    $scope.loadAds = function() {
        $http.get('http://localhost:8080/pederofer/ads/get.action').then(function(result) {
             $scope.ads = result.data;
        });
    };
}

It might not be exactly what you're looking for, but it could spark some new ideas for you.

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

Improved efficiency in CSS for left transition animations

Here is the current code I am using: .s2 { top: 150px; left: 20px; position: absolute; transition: left 300ms linear; } I am currently updating the left position dynamically using JavaScript based on scroll events. However, I have noticed that th ...

Modify the angular ui-view within an ng-repeat loop

Utilizing multiple named ui-views within a single controller has been successful when defining them in the HTML file, like so: <div class="box"> <div ui-view="selector"></div> <div ui-view="widget1"></div> <div u ...

Having trouble establishing a connection between MongoDB and a Node.js Express server on my local machine

While attempting to establish a connection between mongoDB and nodejs express using the post method, I added a logger that should display a message confirming that the database is connected once nodejs listens to mongoDB. However, I encountered an issue wh ...

Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation. 11 2 4 4 5 6 10 8 -12 The task at hand is to calculate the sum along the primary ...

What is the process for integrating Socket io into an external JavaScript file that is connected to an HTML file?

Currently, I am utilizing node js, socket io, and express to develop a multiplayer web game. To begin, the server initiates and listens on port 2000. Upon visiting localhost:2000, the file lobby.html is transmitted using: //app.js const express = require ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

Troubleshooting JSON Array Index Problems

I'm having trouble reaching index 3 in the array using the javascript options on my webpage. The final question "are you satisfied with your choice?" is not showing up for me. I'm not sure what I might be missing or doing incorrectly in this sit ...

Is it possible to adjust the size of a p5.js canvas within a bootstrap Div container?

I am attempting to incorporate a p5js canvas into a bootstrap grid structure. My goal is to have each div within the grid contain its own unique p5js canvas, which should adjust in size when the browser is resized. Below is my bootstrap grid setup, showca ...

Navigating in a Curved Path using Webkit Transition

Currently, I am working on a simple project to learn and then incorporate it into a larger project. I have a basic box that I want to move from one position to another using CSS webkit animations and the translate function for iOS hardware acceleration. I ...

Managing the "Accept Cookies" notification using Selenium in JavaScript

As I use Selenium to log in and send messages on a specific website, I am faced with a cookie popup that appears each time. Unfortunately, clicking the accept button to proceed seems to be quite challenging for me. Here is an image of the cookie popup Th ...

React-Leaflet continuously updates the map with the "MouseMove" event

I'm looking to implement a feature in my React app that displays the geographic coordinates as the mouse moves. However, I've noticed that using "Mousemove" causes the map to be continually redrawn with all objects each time, resulting in poor pe ...

What is the process for bundling a separate JavaScript file with Webpack5?

I am new to the world of webpack. I have 2 javascript files and I want to designate one as the main entry file. However, for the other file, I only want to include it in specific files. For example, looking at the file structure below, main.js is my entr ...

What is the best way to ensure that the state is updated only when the user begins typing in a text

I am currently working on a text editor-related code and my main focus is to update the state of the editor only when the user starts typing in the editor. The state should be updated under the following scenarios: 1. Update the state when the user begin ...

Node.js application experiencing an undefined Angular variable

Hi there, I recently started learning node.js and decided to work on an open-source application that uses it. However, when trying to run the application, I encountered the following error message. I believe it's a minor configuration issue, but I can ...

Can a package-lock.json file be created without running an npm install command?

Is there a way to create only a package-lock.json file without having to redo the npm install process? I'm looking to generate the lock file without reinstalling any of the package files. Is this achievable? ...

When I clicked on the event in Javascript, the result was not what I expected

I am currently working on a web project centered around cooking recipes. In order for users to add ingredients to their recipes, they must input them one by one into a dynamic list that I am attempting to code using jQuery (AJAX). My issue arises when a u ...

Move two markers on Google Maps simultaneously

After researching various articles and posts on Stack Overflow about selecting multiple markers in Google Maps, I have been unable to find a solution for dragging two markers simultaneously. While I've managed to make it work so that one marker can tr ...

Guide on incorporating a refresh button to automatically update information from a database in MaterialUI's Datagrid

Recently diving into JavaScript, I encountered a common issue: The data for my table is sourced from a MySQL database through Axios Whenever CRUD operations are performed in the web app, the database is updated accordingly Although backend changes ...

Tips on automatically focusing on an input within a Semantic UI React dropdown

I'm attempting to automatically focus on an input located within a Semantic UI React dropdown by using a ref, but unfortunately, it's not functioning as expected. The input should be focused when the dropdown is opened. Check out the code sandbox ...

There seems to be a problem with the Chart property getter as it

I'm in the process of creating an object that corresponds to chartJS's line-chart model <line-chart :data="{'2017-05-13': 2, '2017-05-14': 5}"></line-chart> There is an API I utilize which returns a standard arra ...