The closure in question received an undefined Angular parameter

Here is something similar to what I have:

$scope.fetchData = function(path, save_to) {
    $http({method: 'GET', url: 'http://localhost:8001/www-root/' + path}).

         success(function(data, status, headers, config) {
             console.log("Success:  " + data);
             save_to = data;
         }).

         error(function(data, status, headers, config) {
             alert("Error: " + status);
         });
    });

When I use the function like this:

$scope.fetchData("get_users.pl", $scope.users);

The function retrieves the data from the server properly, but the $scope.users variable remains undefined. The question arises - why is that so?

Answer №1

Instead of passing in the variable, just return the promise and handle it per-call:

$scope.getStructs = function (path) {
 return $http({
     method: 'GET',
     url: 'http://localhost:8001/www-root/' + path
 });
}

$scope.getStructs("get_users.pl").
 success(function (data, status, headers, config) {
     console.log("Success:  " + data);
     $scope.users = data;
 }).
 error(function (data, status, headers, config) {
     alert("Error: " + status);
 });

Edit:

It seems like you are looking to make this reusable by creating a factory that can be injected into any controller. Here's an example of how you can achieve that:

(function() {
  function StructFactory($http) {
    return {
      get: function(path) {
        return $http.get(path);
    }
  }
  angular.module('MyFactories', [])
         .factory('StructFactory', StructFactory);
})();

Include the module in your app module:

app = angular.module('myApp', ['MyFactories']);

Then include the factory in your controller:

(function() {
  function MyController($scope, StructFactory) {
    $scope.getStructs = function() {
      StructFactory.get('get_users.pl')
        .success(function(data) {
          $scope.users = data;
        })
        .error(function(data) {
          console.log('Error: ' + data);
        });
  }
  app.controller('MyController', MyController);
})();

Now you have the flexibility to use the factory in multiple controllers and easily add more methods as needed.

Answer №2

The reason for this behavior is that the argument being passed to the function is simply a reference to the original variable.

var x = 20;
function y(argument){
  argument++;
  console.log(argument);
}
// a temporary variable 'temp' is created with the value of `x`, then 'temp++' and 'console.log(temp)' are executed
y(x); //21
// the original variable `x` remains unchanged
console.log(x); //20

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

I am having trouble with the Array Reverse function, it's not functioning properly

Take a look at this React JS code snippet: poll() { var self = this; var url = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40'; $.get(url, fu ...

What is the best way to extract a thumbnail image from a video that has been embedded

As I work on embedding a video into a webpage using lightbox, I'm looking for advice on the best design approach. Should the videos be displayed as thumbnails lined up across the page? Would it be better to use a frame from the video as an image that ...

Changing JavaScript functions into jQuery functions

Currently, I have this Javascript function that I am interested in converting to jQuery: function confirm() { var http = new XMLHttpRequest(); var url = "index.php?tag=' . $dt . '"; var params = "confirm_ref=' . urlencode(encry ...

Integrate fullCalendar event creation with Spring MVC using an AJAX request

I am looking to integrate a new event into fullCalendar and send this event as a JSON object to the server side, which is running on SpringMVC, through an AJAX request. However, every time I make the request, I receive a "400 Bad Request" response. Here i ...

Whenever I press a button, the data fails to be sent to the changePassword.php file using ajax in jquery

I tried to use this form to send data to changePassword.php, but unfortunately, the data did not get sent. <form class="form-horizontal" method="post"> <div class="form-group"> <label for="inputName" class="col-sm-2 control-labe ...

Implementing dynamic content updating in WordPress by passing variables and utilizing AJAX

Currently, I am working on a shopping page that displays a list of all the stores. To streamline the user experience, I have created a sidebar containing various categories and implemented pagination within the store listings. These lists are generated thr ...

Utilizing JavaScript to dynamically set a CSS file from an API in AngularJS

I am currently facing an issue with integrating a CSS file returned by an API into my entire website. Since the URL of the CSS file keeps changing, hard coding the URL is not feasible. While I have successfully implemented this on 'view1', my goa ...

What is the best way to duplicate a tag that contains multiple other tags with attributes?

My form, named 'myForm', needs a div tag with the id 'original' to be added every time I click a button. Can someone help me figure out how to add these tags? The new tags should appear after the original one, but still within myForm. ...

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

Dealing with an empty req.body parameter in a NodeJS function for a Rest API using ExpressJs and sequelize

Looking for assistance with integrating ExpressJS and sequelize. I have a main function (fullaccount.js) that needs to invoke two functions ("accoun.js" and "people.js") receiving data in "fullaccount.js" for processing. However, while req.body is ready in ...

One effective way to create a dynamic and engaging multi-step process using a combination of AJAX, jQuery

In PHP, the steps are counted and stored in a session to prevent going back to the beginning when updating or refreshing the page. The value is retrieved using the variable $step. <?php session_start(); if ( !empty($_SESSION['datos_form' ...

Imitate adjustment of orientation without the need to resize the browser window

Is there a way to simulate page portrait orientation on a PC browser without resizing the window? In my HTML code, I have a <div> element that displays content dynamically based on screen orientation. Is it possible to use JavaScript to trick this & ...

Incorporating the JqueryUI menu into an AngularJS project

We are facing an issue with integrating JqueryUI menus into our AngularJS application. In our Layout.js file, we are attempting the following: OURApp.controller('leftBarCtrl', ['$scope', function ($scope) { $scope.init = function ( ...

Modify the text tone within a specific cell

Welcome to my unique webpage where I have implemented a special feature. The text highlighted in red represents the unique identifier for each individual cell. Interestingly, below there is an input field containing the code "0099CC", which corresponds to ...

Creating plugin-based applications using HTML5

I am new to developing web applications and want to create an HTML5 cross-platform application that resembles the startup page of Windows 8, displaying multiple windows for users to choose from. I need guidance on how to start this project. I would like ...

How to capture and log request and response data when using the HttpService in NestJS?

Is there a way to log requests, responses, and errors using the HttpService within the HttpModule? In the past, I have used Interceptors with AXIOS. While HttpService wraps axios, I'm having trouble adding interceptors. There doesn't seem to be ...

modifying variable values does not impact what is displayed on the screen

I'm currently facing an issue with AngularJS. I have two HTML blocks within an ng-repeat and I need to display one of them at each step. <div class="col-md-3" style="margin-top:80px" ng-init="checkFunction()"> <div id="left_group_stage"& ...

Exploring the similarities between using jQuery AJAX post and Angular

In my current project, I have a legacy application that relies on jQuery and unfortunately cannot incorporate Angular at this time. For one specific task, I need to make an AJAX POST request to consume a web service using jQuery. Interestingly, the same ...

Are arrays being used in function parameters?

Can the following be achieved (or something similar): function a(foo, bar[x]){ //perform operations here } Appreciate it in advance. ...

Using jQuery: How can we manipulate the data returned by sortable('serialize') on a list?

Using jQuery, I have successfully retrieved the positions of a sortable list by using 'serialize' as shown below: var order = $('ul').sortable('serialize'); The variable 'order' now contains this data: id[]=2& ...