Transferring information to a different scope

Here is the current code implementation:

$http.get("http://localhost/app/api/Suppliers").success(function(response) {
    $scope.dataSource = response;
    console.log($scope.dataSource);
    $scope.safeApply(function() {
        $scope.settings.columns[3] = $scope.dataSource;
    });
}); 


$scope.settings  = {
    colHeaders: ["Code", "Comments"],
    contextMenu : ["row_above","row_below","remove_row"],
    colWidths: [100, 100],
    columns : [
        {   type: 'dropdown',
            source: ['Not Started', 'In Progress', 'Completed']
        },
        {},
        {},
        {   type: 'dropdown',
            source: $scope.dataSource,
        }
    ]
};

The issue at hand is that $scope.dataSource is currently undefined, resulting in no data being displayed. How can this be resolved?

UPDATE: While the $http call successfully retrieves the data, the problem lies in the fact that when calling source: $scope.dataSource within the settings, it remains undefined.

Answer №1

When making a request to the server, the controller will compile and then the success function will be entered.

If you declare your array inside the success of your request, it's better to declare it outside like this:

$scope.dataSource = []

$http.get("http://localhost/app/api/Suppliers").success(function(response) {
    $scope.dataSource = response;
    console.log($scope.dataSource);
    $scope.safeApply(function() {
        $scope.settings.columns[3] = $scope.dataSource;
    });
}); 

UPDATE

Try this:

$http.get("http://localhost/app/api/Suppliers").success(function(response) {
      $scope.dataSource = response;
      console.log($scope.dataSource);

      getSetting();

      $scope.safeApply(function() {
        $scope.settings.columns[3] = $scope.dataSource;
      });
    });


    var getSetting = function() {
      $scope.settings = {
        colHeaders: ["Code", "Comments"],
        contextMenu: ["row_above", "row_below", "remove_row"],
        colWidths: [100, 100],
        columns: [{
          type: 'dropdown',
          source: ['Not Started', 'In Progress', 'Completed']
        }, {}, {}, {
          type: 'dropdown',
          source: $scope.dataSource,
        }]
      };
    }

Answer №2

Before diving into the code, it's important to understand that when you set $scope.settings = {...}, the $http request may still be in progress. Instead of writing

{
  type: 'dropdown',
  source: $scope.dataSource,
}

You can simply use

{
  type: 'dropdown',
  source: null,
}

Once the $http call is completed, you probably want to update the source property. But in your current implementation, you are replacing the entire $scope.settings.columns[3] object instead of just updating its source.

Here's a better approach:

$http.get("http://localhost/app/api/Suppliers").success(function(response) {
  $scope.dataSource = response;
  console.log($scope.dataSource);
  $scope.settings.columns[3].source = $scope.dataSource;
}); 

It's worth noting that I've removed the safeApply, which is considered an anti-pattern. The digest cycle will be triggered automatically by the $http call.

Answer №3

Discovered the solution!

$scope.providers = [];

$http.get("http://localhost/i95/api/Providers").success(function(data, status, headers, config) {
    for(var x = 0; x < data.length; x++) {
        $scope.providers.push(data[x].firm);
    }
    console.log($scope.providers);
}); 

Therefore, implementing a global variable and utilizing the push method resolved the issue.

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

What is the best way to upload images and generate permanent links for them using Express.js?

After successfully implementing the upload-part feature to my website, I encountered an issue. When I try to upload a file that is not a picture, the website displays an empty bracket []. My intention is to reject any non-picture uploads altogether. I am ...

Sort information based on the initial letter

My challenge is to accurately filter data by the starting letter only, not including middle letters. For example, if I have the word "Karnataka" and want to filter by the letter "K", searching with middle letters like "rna" still filters the result. Howe ...

Angular2 - How to track or listen for (click) events on dynamically inserted HTML elements

I'm trying to inject a string with a dynamically retrieved (click) event into an Angular2 template. Since this string is fetched from the back-end after the DOM is loaded, Angular doesn't recognize the injected event. Here's an example of t ...

Step-by-step guide on deploying an Angular and Express project to Google App Engine

I am in the process of deploying my app to Google App Engine. I have already set up App Engine and installed gcloud on my local machine. While I have been successful in deploying some projects, I have only done so for Angular applications. My goal now is ...

Is $resource causing $update to not be recognized as a function?

Need assistance with updating a document using two ids in my API root $resource("http://192.168.0.2:3060/product/:subid/:productid",{"subid": "@subid"},{"productid": "@productid"},{update:{method:"PUT"}}); Encountering an error stating: subproduct.$upda ...

How do I make the dropdown menu in a navbar stretch horizontally to cover the entire width of the page container?

When I hover over an item in the navbar, a horizontal dropdown menu currently opens as shown below (note the width of the dropdown menu): https://i.sstatic.net/824OVkWT.png What am I aiming for? I want to expand the horizontal dropdown menu like in the i ...

Angular JS does not acknowledge null values

Within my controller, the variable $scope.test is assigned a value from the server. When this value is null, line 1 of the code below prints 'null', however it still enters the else condition. I have attempted to use $scope.test != null and $scop ...

Using custom middleware for asynchronous actions is essential as actions must be in the form of plain objects - Feeling Confused

It has been a challenging week, as I am facing an issue with the error message: Actions must be plain objects. Use custom middleware for async actions. This problem is related to the following code snippet: const login = await container.props().login(ema ...

jsLint reports an unusual assignment error during type casting

When coding in JS, I rely on both the google-closure compiler and jsLint tool. The closure compiler requires proper JSDoc tags to avoid errors, which means I often need to cast variables to the correct type. The code below works fine with no compiler warni ...

Updating the span element upon click in jQuery

I have this JavaScript code snippet that I am working with: $('a').click(function() { $('a span').first().toggleClass('hide'); $('a span:nth-child(2)').toggleClass('display'); }); .hide { display:none; ...

Sort by various intricate attributes

My dataset looks somewhat like this:- [ { rootGroup: "group1", secondGroup: false, items: [ {name:"Ram"}, {name:"Mohan"}, {name:"Shyam"}, ] }, ...

Even if the parameter is not set in the function, it will still function properly

How can I call a function, regardless of whether the parameter is set or not? What is the correct way to achieve this? select(); select($response_message); function select($response_message) { .... } ...

Issue with conditional comment in IE 8 not functioning as expected

Struggling with changing the SRC attribute of my iFrame specifically for users on IE 8 or older. This is the code I have written: <script> var i_am_old_ie = false; <!--[if lte IE 8]> i_am_old_ie = true; <![endif]--> </script> ...

Utilizing 2 Controllers and 1 Value with AngularJS

Exploring the realm of global variables while honing my skills in AngularJS's factory and service functionality led me to encounter a perplexing error. The issue arises when two controllers attempt to share a global variable, triggering the following ...

Tips for ensuring Node.js waits for a response from a substantial request

When uploading a large number of files, the process can take several minutes. I am currently using a multi-part form to post the files and then waiting for a response from the POST request. However, I am facing issues with timeouts and re-posting of files ...

Looking for mouseover tooltips in three.js?

Currently, I am working on loading an object similar to this demo. My goal is to display a tooltip or infobox when hovering over a specific part of the object. For example, upon clicking the top button, I would like a tooltip to appear above the box. I hav ...

Output each element of an array in Vuejs2 with a line break between each

I am currently working with vuejs2 and have a select tag where a person is selected, with their address properties directly bound to the element. I need to display the address of the selected person. I attempted to use an array in order to print out the el ...

Tips for toggling a menu by clicking a link

I have a Navbar component with a hamburger menu. When the hamburger menu is clicked, I want to display the menu component, which is separate. To achieve this, I passed data through props and made it work. Now, I want the menu to close when clicking outsi ...

What are some effective ways to optimize my Javascript and CSS files for a smaller size?

For those dealing with a high volume of Javascript and CSS files, what strategies are recommended for minimizing file sizes? ...

The themes showcased in the Bespoke.js documentation and demo exhibit unique designs

Recently, I stumbled upon an incredible HTML5 framework for presentations. For more information, you can check out the documentation here. You can also view a demo of the framework by visiting this link. However, I was disappointed to find that the caro ...