user6440175 user6440175 - 1 month ago 5
AngularJS Question

Try to create similar to preexisting javascript function

I am trying to create a similar javascript function to the loadAllOriginal.
But the value of the variable allEmployees is a list with emplooyee objects(ID,FirstName,LastName).How can I do that?
I am trying to use this method with the autocomplete from this page:
https://material.angularjs.org/latest/demo/autocomplete

function loadAllOriginal()
{
var allEmployees = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
Wisconsin, Wyoming';

return allEmployees.split(/, +/g).map(function (employee)
{
return
{
value: employee.toLowerCase(),
display: employee
};
});
}

function loadAll()
{
var allEmployees = $http.post('../Admin/GetUsers/');
..........
}

Answer

Okay, so I made a bad assumption that you knew how to get the records loaded into the allEmployees variable. I have updated my answer to include how to get data from an asynchronous function call and then subsequently be able to use that data.

One way that you can get this to work is by using a deferred object and returning a promise from your loadAll() function. This can be done using the $q service that is built into angular. Here is one way to implement it:

function loadAll() {
    return $q(function (resolve, reject) {
        $http.post('../Admin/GetUsers/').then(function successCallback(response) {
            resolve(response.data.map(function (employee, index) {
                return {
                    value: employee.ID,
                    display: employee.FirstName + " " + employee.LastName
                }
            }));
        }, function failureCallback(response) {
            reject("Error!");
        });
    });
}
var allEmployees = [];
loadAll().then(function success(employees) {
    allEmployees = employees;
}, function failure(message) {
    console.log(message);
    allEmployees = [];
}).then(function (){
    console.log(allEmployees);
    // rest of your code that uses the allEmployees variable goes here...
});
Comments