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

AngularJS lazy loading for a Bootstrap carousel slider

I am looking to implement lazy loading in Bootstrap CAROUSEL similar to this example: example <img data-lazy-load-src= However, I am using ng-src (AngularJS) to fetch images in the slider. How can I modify this example to work with an Angular Boots ...

The YouTube Iframe API encountered an issue while attempting to send a message to an HTTP recipient. The recipient's origin

Encountering an error when using the YouTube Iframe API on Safari 9.1, OS X Yosemite Issue: Unable to post message to http://www.youtube.com. Recipient has origin https://www.youtube.com This problem only occurs in Safari, as other browsers like Firefo ...

Is there a way to transfer ngClass logic from the template to the TypeScript file in Angular?

I am implementing dropdown filters for user selection in my Angular application. The logic for adding classes with ngClass is present in the template: <div [ngClass]="i > 2 && 'array-design'"> How can I transfer this ...

Exploring AngularJS 1.0: Incorporating Dynamic Property Names and Columns into HTML Expressions

I am currently encountering an issue when trying to bind data to angularJs 1.0. I have retrieved the data from the Database using a Pivot Query with Dynamic Column names, however, I am unable to successfully bind the data to the AngularJS html expression ...

Tips for validating a dynamically created form with Bootstrap tabs using jQuery

For my project, I am dynamically creating an HTML form using jQuery. The page consists of five tabs, each with separate previous and next buttons. These tabs are designed using Bootstrap. Can someone please suggest the easiest way to validate this page? Fo ...

Navigating URLs to Single Page Application Routing in Vue.js

I'm new to using vue-router and I'm curious if there's a way to manage redirection in Vue or if there are alternative methods in a node.js environment. For instance, when someone tries to access my site by typing the URL example.com/contac ...

Creating separate Vuex stores for dynamic components

This question really had me stumped for a while. I couldn't find the answer here (asking around didn't help either). However, after conducting some research and seeking advice from various sources, I believe I have finally arrived at a solution t ...

Cross domain Ajax POST requests using CodeIgniter and AjaxBy utilizing CodeIgn

Initially, I would like to clarify ... I own two domains: www.one.com and www.two.com The first domain www.one.com has a form input below <div class="hidden cswrap2"> <h3>Edit Data Mustahik</h3> <div class="cscontent"> ...

Calculate the total length of the nested arrays within an object

Check out this object: const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] } I'm looking to find a way to quickly calculate the sum of lengths of arrays arr1 and arr2. ...

I'm noticing multiple repeated entries appearing when I try to set the cookie - what could be causing

Currently, I am utilizing the library js-cookie instead of my previous use of jquery.cookie. I have encountered an issue related to duplicating cookie entries. There are occasions when I invoke the following method: Cookies.set('my-cookie-name', ...

Transmitting a pair of data points to PHP using ajax POST for querying the SQL database

I am attempting to send two values from a form to another PHP file using the ajax post method. One value is the current input box value, while the other is the value being typed into a different input box which functions as a search box. When I execute the ...

Prevent the border from shrinking upon being clicked

I'm currently working on customizing an accordion using jQuery for the animation effects. However, I am facing an issue where clicking on the accordion header causes the border around the plus sign to shrink in size as well. My goal is to only have th ...

Tips for avoiding event listeners from being triggered multiple times

Implemented an event listener on an HTML element that was retrieved by className within the render method of highcharts, but for some reason, the listener is being triggered twice. The issue seems to be with the onClick handler in the highchart's rend ...

Having trouble with ion-item click not functioning in Ionic 3?

Working on my Ionic 3 project, I have encountered an issue with the ion-item click listener. The scenario is that I am adding text over a canvas and then attempting to change the style of the text (such as font-family, font-size, bold, and italic). The UI ...

Employing ngModel within an (click) event in Angular 4

I have this html code snippet: <div class="workflow-row"> <input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox"> <label>New Workflow</label> <input type="text" *ngIf="new_checkbox" placeholder="Enter ...

How can I add text to an HTML5 SVG similar to using the HTML5 <p> tag?

I am currently working on creating dynamic rectangular boxes and I am facing some difficulties with inserting text into the shapes. The SVG text requires setting x and y coordinates in separate text tags, and doesn't have built-in width and height pro ...

Using an Array as an Argument in a JavaScript Function

Currently, I am utilizing a web service to populate a selection list. Now, I need to repeat this process for multiple selection lists, with the goal of minimizing the amount of code duplication. Below is the function I am using to make the web service call ...

The ActionController is encountering an UnknownFormat error when trying to respond to AJAX requests with js using

I've been scouring the internet for information on this topic, but I'm having trouble understanding how AJAX works with Rails. I've gone through the documentation multiple times and it's just not clicking for me. From what I gather, AJ ...

A guide on accessing $bvToast in Vue class components

I am fairly new to vue.js but I have managed to figure out some things. I initially started with regular js, but then transitioned to typescript with class style vue components. For styling the components, I rely on bootstrap-vue. In my main.ts file, I im ...

AngularJS written plugin in Javascript

I developed an app using Rails and AngularJS. A startup has reached out to me about transferring the technology to their website, but they have limited tech resources. The goal is to create a seamless integration process. The idea is to make it similar to ...