Retrieving the $scope data from within an http.get callback

Would someone be able to assist me with storing the data returned by the $http.get function in a $scope variable for use in my ui-grid control?

I have tried the code below but seem to be missing something simple. I just can't figure out what it is:

app.controller('AdminUsersGridCtrl', function ($scope, $http, uiGridConstants) {

    $http.get('/api/admin/user')
    .success(function (response, $scope) {
        $scope.myData = response;
    })
    .error(function (error) {
        console.log(error);
    });

    console.log($scope.myData);

    $scope.gridOptions = {
      data: 'myData',
      enableFiltering: true,
      columnDefs: [
        { field: 'firstName' },
        { field: 'lastName' },
        { field: 'jobTitle'},
        {
          field: 'email',
          filter: {
            condition: uiGridConstants.filter.ENDS_WITH,
            placeholder: 'ends with'
          }
        },
        {
          field: 'phone',
          filter: {
            condition: function(searchTerm, cellValue) {
              var strippedValue = (cellValue + '').replace(/[^\d]/g, '');
              return strippedValue.indexOf(searchTerm) >= 0;
            }
          }
        },
      ]
    };        

  });

When I check the console inside the success function, it prints undefined. What can I do to access the original $scope inside the $http.get success function?

Answer №1

When I check my console on success, it shows 'undefined'.

However, your console log is not inside the success method. It should be placed within:

$http.get('/api/admin/user')
.success(function (response) {
    $scope.myData = response;
    console.log($scope.myData);
})
.error(function (error) {
    console.log(error);
});

It should not be here:

// order of events..
// #1...first $http
$http.get('/api/admin/user')
.success(function (response) {
    //... #3 third. Now finally response is defined. the end
    $scope.myData = response;
})
.error(function (error) {
    console.log(error);
});

//... #2 second. $scope.myData definitely IS undefined
console.log($scope.myData);

There is a significant difference. Additionally, there is no requirement to use $scope in the success callback. This is not a common practice. Where did you come across this technique?

Answer №2

Is it more beneficial to make a server call by utilizing a service in an external file? In your specific scenario, the $scope does not receive the response due to the code being executed before the service is complete. Consider using a $timeout or a similar approach:

app.controller('AdminUsersGridCtrl', function ($scope, $http, uiGridConstants) {

$http.get('/api/admin/user').success(function (response) {
    $scope.myData = response;
    fillGridOptions();
}).error(function (error) {
    console.log(error);
});

function fillGridOptions() {
$scope.gridOptions = {
    data: 'myData',
    enableFiltering: true,
    columnDefs: [
      { field: 'firstName' },
      { field: 'lastName' },
      { field: 'jobTitle' },
      {
          field: 'email',
          filter: {
              condition: uiGridConstants.filter.ENDS_WITH,
              placeholder: 'ends with'
          }
      },
      {
          field: 'phone',
          filter: {
              condition: function (searchTerm, cellValue) {
                  var strippedValue = (cellValue + '').replace(/[^\d]/g, '');
                  return strippedValue.indexOf(searchTerm) >= 0;
              }
          }
      },
    ]
};

}

});

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

Serialization of select value in Ajax/PHP form submission

Currently, the form is sending the correct information but it is missing the state field. The issue arises because the value of the state field is not fixed and depends on the selected state. How can I address this? JS: $('#sendFormBtn').live(& ...

What is the proper way to select the <ul> element within an FTL template?

Can someone provide guidance on how to target a <ul> container within a freemarker template using JavaScript? My goal is to display the content of this specific <ul> element in my FreeMarker template on the web page. Any suggestions on how I ...

Ways to activate the JavaScript/AJAX script upon the dropdown value modification

I am currently working on a Django project where I want to execute a JavaScript/AJAX script when the value of a dropdown changes. Interestingly, the same code functions properly for a button but not for the dropdown. Below is the HTML code containing the ...

The data insertion query in MYSQL seems to be malfunctioning

I am facing an issue with inserting data from a form into a database table named "sumation". Despite using PhpStorm IDE, I am getting errors indicating that no data sources are configured to run the SQL and the SQL dialect is not set up. Can anyone help ...

Tips on moving information from one form to another after referencing the original page using Javascript and HTML

Imagine this scenario: A page with three text fields, each with default values. There is also a hyperlink that performs a database lookup and returns parameters to the same page where the hyperlink was clicked. The goal is for the text boxes to be automa ...

The syntax for an AngularJS controller using the "as" keyword

Incorporating AngularJS 1.6.9 with AngularJS Material has been a challenge for me. I am attempting to integrate a menu item feature following the basic usage, but unfortunately, it did not work as expected due to structural differences. After reviewing th ...

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

Numerous Levels of Dropdown Menus

I am looking to implement a feature on a web page where users can select multiple vehicles using JQuery. The idea is that selecting the brand in the first dropdown will populate the second dropdown with the models available for that specific brand. The ...

Continuously spinning loading icon appears when submission button is triggered

We are currently experiencing some issues with our mobile forms. Our users utilize a mobile form to submit contact requests, but the problem arises when they hit 'submit' - the loading icon continues to spin even after the form has been successf ...

Tips for adding styles to the first and last elements of a printed page

I have created a dummy code example that generates multiple paragraph elements with some text in it. However, I need to add borders to the first and last elements to enhance the design. Here is the code snippet: <!doctype html> <html> <he ...

Send image data in base64 format to server using AJAX to save

My goal is to store a base64 image on a php server using the webcam-easy library (https://github.com/bensonruan/webcam-easy). I added a button to the index.html file of the demo: <button id="upload" onClick="postData()" style=" ...

Leveraging dynamic keys with v-for in Vue.js

In my Vuejs project, I am currently developing a reusable table component that looks like this: Table Component Structure: <template> <div> <table class="table"> <thead> <tr> ...

What is the process for transmitting data in JSON format generated by Python to JavaScript?

Utilizing Python libraries cherrypy and Jinja, my web pages are being served by two Python files: Main.py (responsible for handling web pages) and search.py (containing server-side functions). I have implemented a dynamic dropdown list using JavaScript w ...

Utilizing Node Js and Selenium webdriver, what is the process of dragging and dropping an element from its current position to a new position just below it?

After multiple attempts, I have come to realize that the following code is ineffective. driver.findElement(By.xpath(xpath)).then(function (element1) { driver.findElement(By.xpath(xpath)).then(function (element2) { ...

disable angular ui router functionality for specific links

Currently, I am looking to implement the bootstrap accordion in my Angular application. The angular ui-router is being used for navigating through different pages. However, I have come across an issue where the accordion requires an <a href="#Collaps ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

Can you please provide instructions on how to implement an ng-repeat loop within an HTML table?

<thead> <tr> <th ng-click="sortData('firstname')"> Firstname <div ng-class="getSortClass('firstname')"></div> ...

When checking for errors with console.log(errors) in Ajax, it may return undefined due to server-side

I'm looking for a way to alert the user about validation errors coming from PHP. I am currently using Laravel 5.3 to build the form and Ajax to retrieve error messages. Below is my JavaScript code: $.ajax({ url: '/artistPost', typ ...

Is there a way to utilize redux to trigger the opening of my modal when a button is clicked?

I'm facing a challenge with opening my modal using redux when clicking <CheckoutButton/>. Despite my efforts, the modal keeps appearing every time I reload the browser. I've reviewed my code but can't pinpoint the issue. What am I doin ...