Tips for extracting function data and storing it within scope after resolving a route in AngularJS

Is there a way to fetch data from a function and store it in the scope using resolve in an AngularJS route?

For instance:

.state('list.employee_list', {
            url: "/employee_list",
            templateUrl: "views/list/employee_list.html",
            data: { pageTitle: 'Employee list' },
            resolve: {
                "employeesCollection" : function(){
                    alert("LOAD");
                    $scope.myData = myFunction($scope);
                    alert("finished load, now load view");
                }
            }
        })

The main concept here is to retrieve data for a table before rendering its view, ensuring that the table won't be empty. The data retrieval function communicates with Parse.com.

UPDATE:

config.js

.state('list.employee_list', {
            url: "/employee_list",
            templateUrl: "views/list/employee_list.html",
            data: { pageTitle: 'Employee list' },
            controller: employeeListCtrl,
            resolve: {
                employeesCollection :  employeeListCtrl.loadData(companyID)
            }
        })

controllers.js

function employeeListCtrl($scope, employeesCollection){
    $scope.employeesCollection = employeesCollection;
}

employeeListCtrl.loadData = function(companyID){
    var employeesCollection = [];
    var User = Parse.Object.extend("User");
    var promise = new Parse.Promise();
    var query = new Parse.Query(User);
    query.equalTo("companyID", companyID);
    query.find().then(function(results) {
        for (var i = 0; i < results.length; i++) {
            var estado = results[i].get("sendTest");
            if(estado == "no"){
                results[i].status = "{{ 'FREE' | translate }}";
            }else if(estado == "yes"){
                results[i].status = "{{ 'TEST_SENT' | translate }}";
            }
            console.log(results[i].get("lastName"));
            employeesCollection[i] = results[i];
        }
    }).then(function(redirect) {
        // All tasks completed!
        //window.location.href = "#/list/employee_list";
        promise.resolve();
        console.log("LOADED");
        return employeesCollection;
    });
}

views/list/employee_list.html

<tr ng-repeat="row in employeesCollection">
                            <td>
                               {{row.get("firstName")}}
                            </td>
                            <td>
                                {{row.get("lastName")}}
                            </td>
                                <span class="label label-primary">{{status}}</span>
                            </td>

                        </tr>

Answer №1

To achieve this goal, follow these steps:

Start by creating a service that retrieves your data. Let's name this service MyData:

app.factory('MyData', ['$http', function ($http) {

    var obj = {};

    obj.get = function (myendpoint) {
        return $http.get('https://some/endpoint/to/get/data/'+myendpoint).then(function (results) {
            return results.data;
        });
    };

    return obj;
}]); 

Next, integrate this service into the resolve function in your $routeProvider:

.when('/events', {
  templateUrl: 'views/events.html',
  controller: 'EventsCtrl',
  resolve: {
    preloaded: function(MyData) {
      return MyData.get('allevents');
    }
  }
})

Then, in your controller, utilize the resolve object to access your data:

app.controller('EventsCtrl', ['$scope', 'preloaded', function ($scope, preloaded) {

    $scope.allevents = preloaded;

}]);

Answer №2

It appears that the best approach would be to first load the view and then invoke your function within the controller to retrieve the data from Parse.

Once you have obtained the data, simply execute $scope.$apply() to refresh the bindings, which will result in the table being updated. Following this method is recommended as it enables you to display a loading animation on the table.

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

is it possible to use jquery event listeners on a webpage that uses angular.js?

We are currently working on a page that utilizes angular.js, incorporating ng-scope classes and ng-click attributes within several <tr> elements. To enhance the functionality of the page post-implementation, we are considering using greasemonkey. Sp ...

Extracting information from a nested JSON object **INCLUDING IDENTIFIERS** through an Angular HTTP GET request

Hey there! I'm fairly new to Angular and dealing with JSON Objects, and I'm currently facing a challenge in extracting data from nested objects. The task itself isn't too complicated, but the tricky part lies in the fact that the JSON objec ...

Unable to locate video identifier on ytdl

Lately, I have been working on developing a music bot for Discord. I have successfully managed to make it join and leave voice channels flawlessly, but playing music has proven to be quite challenging. For some reason, the play and playStream functions do ...

Creating AngularJS variables with dependencies on integer values

Hello, I am a brand new developer and I am currently working on creating an expenses calculator. The goal is to have the sum of inputted integers from a table, each with a default value, become the integer value of another variable. However, I seem to be m ...

Is there a way to extract the timestamp in JavaScript from a string that includes the name of the timezone database?

Given the string: "2022/05/01 03:10:00", I am seeking to create a Date object with Chile's UTC offset. The challenge lies in the fact that due to Daylight saving time (DST), the offset changes twice annually. How can I obtain that Date obj ...

The seamless integration of AngularJS and the chosen library is proving to be

When I use a chosen select to load data from a JSON file in an AngularJS application, the data loads successfully with a standard HTML select. However, if I switch to using the chosen select, the data does not load. I understand that the data is fetched af ...

Removing items from a todo list in JSX without relying on props or state

I am facing a challenge with utilizing a function to delete an item from an array when clicking the delete button. I am seeking a solution without relying on props or state. Could someone please point out where I may be making a mistake? The item appears ...

Ways to incorporate gradual transparency to an element using HTML and CSS

I have a list item that I want to visually disappear into the horizon during a JavaScript event. I am not looking to animate it, more like applying a filter effect. Is there a way in HTML/CSS/JavaScript to dynamically add gradual transparency without chang ...

Utilizing React Refs to Retrieve Value from HTML Select Element

I am currently working on a form that includes the use of an HTML select element. <select className="form-control" id="ntype" required > <option value = "">None</option> <option value = "1">1</option> < ...

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

Tips for efficiently storing data in the Laravel database using Ajax

I'm attempting to upload a product with multiple images to the database without refreshing the page. Despite not encountering any errors in the console, I am seeing a long block of text that starts like this: <script> Sfdump = window.Sfdump || ...

PLupload does not support Flash runtime in Internet Explorer 8

I am facing a dilemma with a basic JavaScript function placed within the $(function() { ... }); block. var uploader = new plupload.Uploader({ runtimes: 'html5,flash,silverlight', browse_button: 'pickfiles', c ...

Retrieve a specific column value upon button click in HTML and JavaScript

I am faced with a table containing multiple columns, each row equipped with an edit button. https://i.sstatic.net/3S5VP.png Upon clicking the edit button, a modal view pops up where users can input values that are then sent via AJAX to my controller. ht ...

Interacting with distant servers within XD plugins

Currently in the process of developing an XD plugin, with a goal of fetching images from a remote server. Is this achievable and are there specific APIs that can facilitate this task? ...

What makes a single numerical value in an array suitable for basic arithmetic operations?

I find it puzzling how an empty array or an array with just one "numerical" value can be used in various calculations. [] * [] === 0 // true [2] * [2] === 4 // true ["2"] * ["2"] === 4 // true Interestingly, not every operator behaves in the same way. ...

Attempting to rearrange the table data by selecting the column header

In an attempt to create a table that can be sorted by clicking on the column headers, I have written code using Javascript, HTML, and PHP. Below is the code snippet: <?php $rows=array(); $query = "SELECT CONCAT(usrFirstname,'',usrSurname) As ...

Using environmental variables in Nuxt 2 or Nuxt 3 - a step-by-step guide

I have an .env file located in the root of my project. In my nuxt config, I am using variables to configure ReCaptcha as shown below: import dotenv from 'dotenv' dotenv.config() export default { modules: [ ['@nuxtjs/recaptcha&ap ...

Designing personalized buttons on React Google Maps

Currently tackling a personal project that involves react-google-maps, but I'm struggling to display custom buttons on the map. My goal is to create a menu button that hovers over the map, similar to the search bar in the top left corner of Google Map ...

Issue: Incorrect comparison of two dates leading to inaccurate results

I have been attempting to compare two dates within a UI-GRID, and although I have the dates in the correct format, it seems to always provide a false result. Below is the code: filters: [{ condition: function (term, value) { if (!term) return ...

Exploring the Printing Options in Opera using ASP.NET

When using JavaScript, I encountered an issue where the print dialog box would not appear. The new window would open successfully, but the print dialog was missing. This problem only occurred in Opera, while IE, Chrome, and Mozilla worked fine. I have rese ...