Utilizing AngularJS to implement a typeahead feature that interacts with a

Currently using AngularJS in conjunction with C# webapi.

I'm working on creating an input control that utilizes typeahead to display returned data as the user types.

Below is how I have set up the typeahead:

HTML:

  <input type="text" name="uName" ng-model="uName" autocomplete="off" required class="form-control input-medium" placeholder="Enter user name..."
   typeahead="uName for uName in getUserNames($viewValue)" />

Controller:

    $scope.getUserNames = function (search) {
        myService.getUserNamesFromApi(search).then(function (response) {
            $scope.foundNames = [];
            if (response.length > 0) {
                for (var i = 0; i < response.length; i++) {
                    $scope.foundNames.push({ 'uName': response[i].uName });
                }
                return $scope.foundNames;
            }
        });
    };

The data returned from the API is structured as an array, for example:

0: {fName: "Adam", lName: "Smith", uName: "asmith123"},
1: {fName: "John", lName: "Bambi", uName: "jbambi456"}

And so forth...

My goal is to extract the uName part and add it to my array before returning it. However, currently the code displays nothing without any errors. What could I be overlooking?

Answer №1

It needs to look like this,

 typeahead="name as name.name for name in fetchNames($viewValue)" />

Answer №2

Ensure you remember to return a promise from your getUserNames function. This is vital for typeahead to load the asynchronous collection while typing. Also, make sure to return $scope.foundNames; outside of the if statement.

$scope.getUserNames = function (search) {
    // Don't forget to return the promise.
    return myService.getUserNamesFromApi(search).then(function (response) {
        $scope.foundNames = [];
        if (response.length > 0) {
            for (var i = 0; i < response.length; i++) {
                $scope.foundNames.push({ 'uName': response[i].uName });
            }
        }
        // Return the result here.
        return $scope.foundNames;
    });
};

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

Struggling to get a basic HTML form to function with JavaScript commands

In my form, there are two input fields and a button. Upon clicking the button, a JavaScript function is triggered which multiplies the values entered in the inputs. The result is then displayed in a <p> element and evaluated through an if else statem ...

Using Vue.js: Execute a function with a delay, but start the delay over if there is any user input

Imagine a scenario where I have a form that is connected to an API and displays information based on user input. Whenever the user makes changes, such as adjusting the number of results per page, the component should react dynamically by loading new data. ...

Switch out 2 Bootstrap columns for 2 concealed columns with just a click. Utilizing Rails 4 and Bootstrap

Using Twitter Bootstrap 3 for a column system showcasing four similar advertisements at the bottom of the page. Code Snippet: <div class="row similar"> <% @recomended_ads.each do |advertisement| %> <div class="col- ...

Troubleshooting: Mobile Browser Compatibility Issue with Nested Views in Angular-UI Router

For my application, I am utilizing angular ui-router, however, the nested views are only loading for desktop browsers and Chrome for Android. Other mobile browsers like Chrome for iPhone, Samsung Browser for Android, and Safari for iPhone do not show the n ...

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...

Avoid using a for loop to alternate between pushing items into an array

I have a code snippet that currently functions like this: let result = [] const number for (let i = 0; i < number; i++) { result.push(f(i)) result.push(g(i)) } return ( <div> {result} </div> ) The functions f(i) and g(i) each ...

ES6 class properties with undefined constant in Javascript

Currently, I am developing automated end-to-end tests using Protractor with Selenium. I have a class where I intend to store a property to improve the organization of my tests. Below is the specific class: export class Tab { constructor(job) { ...

Refreshing a JQuery select control to reload and re-render the options

I have implemented the following functions to enable searching within a select dropdown using an input text field: The first function triggers the search when a key is pressed in the input field: $( 'input#id_nit_del_cliente' ).keyup(function(e ...

Redirect to the URL with HTTP Basic Authentication enabled

Can my MVC app (website 1) redirect to another URL (website 2) and authenticate automatically? I attempted to use return Redirect("http://login:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0474657777736b7660447373732a7065766 ...

Retrieve data from specified <td> element in an ASP.NET MVC application

Within my View, I am displaying data using a table. Below is the code snippet: @foreach (var item in Model) { <tr > // Table row content here... </tr> } I have buttons with ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...

Mastering the BFCache management in React for optimal performance

Before redirecting to an external payment provider, I display a loading screen to account for longer load times. If the user decides not to complete the payment and navigates back using gestures or the browser's back button, the page is pulled from t ...

ReactJS: A step-by-step guide to loading JSON data from a local source

I have been working on a script to display JSON data, currently I am loading the data at runtime. How can I modify the code to load it locally instead? Could you please help me take a look at this issue? Thank you! My goal is to turn my script into a libra ...

Navigating between child nodes in an HTML drop down list with multiple options and hierarchical structure

Hey there! I am looking to create a unique HTML hierarchy drop-down menu. It will have multiple levels or options, with each option having the potential for child nodes. When an option has child nodes, an arrow will appear next to it. Clicking on this ar ...

Visualizing dynamic data with Ajax in a column bar chart

Trying to implement highcharts column bar charts, but facing issues with refreshing the data without reloading it. Unfortunately, I don't have access to the code I used at work to resolve this. Considering setting up a loop to run multiple times with ...

A guide to sending props to a CSS class in Vue 3

I need to develop a custom toast component that includes a personalized message and class. While I have successfully passed the message as props, I am encountering difficulties in applying the bootstrap class. Component File: Toast.vue <script ...

The building process of Ember encountered an error due to a problem with the broccoli builder

I'm currently working on an Ember project and facing an issue while trying to upgrade the version from 2.8 to 3.5.0. After changing the version and some dependencies, I encountered the following error : Error stack Even after attempting to resolve i ...

How can a producer know when it's time to send a message in NodeJS using ZeroMQ?

After conducting some research on patterns supported by zeromq, I have encountered an issue with the PUB/SUB pattern in my recent project as well as the PUSH/PULL pattern. I am using NodeJS for the zeromq implementation. In my examples (server.js & client ...

Load a PHP page using AJAX that triggers a JavaScript function

My goal is to enhance a progress bar (using Bootstrap) while a PHP page processes data from an AJAX GET request. Currently, the progress bar only updates once the AJAX request is fully completed. Although there is more content on the pages than what' ...