Retrieving data from an anonymous function in AngularJS and outputting it as JSON or another value

Within the following code, I am utilizing a server method called "getUserNames()" that returns a JSON and then assigning it to the main.teamMembers variable. There is also a viewAll button included in a report that I am constructing, which triggers the method "$scope.viewAllTeamMembers = function($event)" as shown below.
The issue I am facing is that initially, the view all button does not display all the values stored in main.teamMembers when the report is first loaded. However, if I navigate to other buttons within the report and return to the viewAll button, it works as expected.
I have noticed that when the JSON is returned from an anonymous source rather than a global variable, the viewAll button functions correctly on the first attempt. I would appreciate your insights on what might be causing this discrepancy.

angular.module('kamApp')
    .controller('MainCtrl', [
        '$q',
        '$rootScope',
        '$scope',
        '$timeout',
        'endpoints',
        'kamService',
        'queries',
        'translations',
        function($q, $rootScope, $scope, $timeout, endpoints, kamService, queries, translations) {

            var getUserNamesRequest = endpoints.getUserNames($rootScope.teamMemberIds).then(function(userData){
                return userData;
            });

            getUserNamesRequest.then(function(userData,$scope)  {

                $rootScope.userNameList = kamService.extractUserNameList(userData);

                main.teamMembers=kamService.concatTeamMemberName(
                    main.teamMembersData,
                    $rootScope.userNameList.list
                );

                main.teamMembers.list = kamService.sortList(main.teamMembers.list, 'role', 'name');  

            });
    }]);

--Directive

    angular.module('kamApp')
    .directive('teamMember', function() {

        return {
            templateUrl: 'views/team-member.html',
            replace: true,
            restrict: 'E',
            scope: {
                teamMembers: '=',
                viewSwitch: '=',
                changeReportTitle: '&'
            },
            link: function($scope) {

                $scope.itemLimit = 4;

                $scope.isOddLength = $scope.teamMembers.list.length % 2 !== 0;

                $scope.viewAllTeamMembers = function($event) {
                    $event.target.style.opacity = 0.6;
                    $scope.viewSwitch.dashboard = false;
                    $scope.viewSwitch.teamMember = true;
                    $scope.changeReportTitle()($scope.teamMembers.objectName.plural);
                };
            }
        };
    });

--HTML Code

 "<div class=\"expand-link inline-block-div\" ng-click=\"viewAllTeamMembers($event)\"> \n"+

Answer №1

When looking at example 1, the usernames variable is set to the promise returned by getUserNames().then() instead of the actual returned value. Additionally, JSON.stringify(userNames); is executed before the AJAX request is completed.

Similarly, in example 2, JSON.stringify(userNames); is also being called before the AJAX request finishes.

The correct approach is to place the code that relies on result inside the then callback.

var result={};

getUserNames($rootScope.teamMemberIds).then(function(userData){
    result = userData;
    // Code that depends on result
});

If you need to run other code that is dependent on the variable being set, you can do so like this:

var result={};

var getUserNamesRequest = getUserNames($rootScope.teamMemberIds).then(function(userData){
    result = userData;
    // Code that depends on result

    // Return the data so that chained promises receive the original data.
    return userData;
});

// Other code that relies on `result` being set.
getUserNamesRequest.then((userData) => {
    // You can use either `result` or `userData` here.
});

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 methods can be used to gather information on a user's browser details, IP address, and location

I am in need of assistance to retrieve the user's browser information, IP address, and GEO location for our asp.net application. This information is crucial for tracking where users are accessing the application from, along with their browser/IP detai ...

The initial component update

I am new to React and currently working on a main component that includes a child component with a table. Upon mounting, I make an API request to fetch data which is then displayed in the table. My issue arises when, after the initial update of the child c ...

The jQuery script is functioning flawlessly in one specific direction

Currently, I am utilizing a basic script to alter the color of elements based on the div being hovered over. While this works smoothly in one direction down the line, when trying to reverse order and backtrack, the colors do not function as intended. The ...

Display a specific element only if another element exceeds a specified height

A snippet of HTML code is given below: <span class="day-number">{{day-number}}</span> <div class="event-box"> <div class="event-container"> </div> <div class="more-events">more ...</div> </div> The .e ...

Receive an odd array element

When I load a single data from the database, it appears as an array. However, I am unsure how to extract the value in label_values. Print_r($results): Array ( [custom_params] => custom_limit="0"|input_label="{\"label_values\":[\"\u ...

Stripping CSS from my HTML using TinyMCE

I have created a custom Javascript function that retrieves the content of an HTML file from my server and then integrates it into a TinyMCE editor. Here is the function: function LoadTemplate(url) { $.post(url, function (data) { // Access the ...

Arrow icon from Material UI for a smaller device

As I work on coding a tab bar, I have encountered an issue where the indicator arrow button () is not displaying when the width of the tab bar goes below 600px. I would like it to appear like this: https://i.stack.imgur.com/PDum9.png However, currently i ...

Enable automatic real-time updates of an Angular view based on changes in the length of

I am curious about how Angular detects changes in a MongoDB collection. I have a variable keeping track of the number of items in my database, and I want the front end to automatically update the display whenever a new item is added from the front end. Is ...

Retrieving information from Firebase after updating it

My goal is to automatically navigate to a specific ID after adding an item to my realtime database. Despite following the documentation's proposed solution, I am encountering issues with its implementation. Following the use of the push().set() meth ...

Is there a way to swap out values in a JavaScript Object for new ones?

I need to update the initial values of myObject with new names: let myObject = [ { name: 'X0', values: 'FALSE,TRUE' } , { name: 'X1', values: 'NORMAL,LOW,HIGH' } , { name: 'X2', values: ' ...

The jQuery toggle functionality seems to be malfunctioning

I have created a form that should toggle (hide and show) with the click of a button, but for some reason it's not working. Can someone please take a look at my code below and let me know what I'm doing wrong? $(document).ready(function () { ...

Interactive Zoomable Tree with d3.js

I am looking to customize the zoomable icicle plot in d3js by incorporating my own data. Unfortunately, I am unable to locate the "readme.json" file for data modification and cannot get the graph to display on my local machine. Where can I find this elus ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

Troubles with Express JS POST Requests

I'm facing an issue while attempting to write code that creates a MongoDB entry using express.js. Every time I test my code with a cURL request, I receive an error message stating "empty response from server". Below is the snippet of my express.js co ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Loop through an HTML table in order to emphasize variations in cells that contain multiple comparison items

I am interested in highlighting variances between the initial row of a table and all other rows based on columns. I have successfully managed to achieve this when each cell contains only one item/comparison. However, I would like to expand this to include ...

Load the index file using any URL parameter in the Express.js Router's "catchall" feature

I have a simple setup for my project, including server.js file in the root directory with the following code: app.use('/', express.static(__dirname + '/public/')); In addition, there is a public folder containing index.html, styles, a ...

What is the best way to keep my layout component fixed in the Next13 app directory?

I am struggling to develop a custom layout component that can retrieve its own data. Despite adding 'cache: 'force-cache'' to the fetch function, the updated content from my CMS is still being loaded every time I refresh the page. Below ...

"Unspecified error in Angular" encountered when implementing Mobile Angular UI in conjunction with Angularfire

I am currently working on developing a mobile app using Mobile Angular UI and integrating it with a Firebase database. However, I keep encountering an error when trying to include Firebase: Uncaught ReferenceError: angular is not defined at angularfire.m ...

Organize a collection of objects based on their individual keys

How can an array of objects be grouped based on keys using vanilla JavaScript, especially when dealing with a large number of records like 10000? Here is a sample object to illustrate: [ { company: "TATA", car: "TATA Indica", color: "Blue" }, { ...