Utilizing JSON data to power autocomplete options in textboxes

This answer is similar to my current project. I am building upon the original Plunker and creating a new Plunker

The original plunker contains a text box with autocomplete functionality using hardcoded options in a list.

In the new plunker, I have implemented a service that fetches information about Stack Overflow badges in JSON format. How can I modify the autocomplete feature to display badge names based on this JSON data?

<html lang="en">

  <head>
    <meta charset="utf-8" />
    <title>jQuery UI Autocomplete - Default functionality</title>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e2f20293b222f3c60243d0e7f607d6077">[email protected]</a>" data-semver="1.3.9" src="https://code.angularjs.org/1.3.9/angular.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
    <script>
      var app=angular.module('app',[]);

      app.factory('badges', ['$http', function($http) {
          return $http.get('https://api.stackexchange.com/2.2/badges?page=1&order=desc&sort=rank&site=stackoverflow')
            .success(function(data) {
              return data;
            })
            .error(function(err) {
              return err;
            });
      }]);

      app.controller('ctrl', ['badges', function($scope, badges){

          // How do I extract a list of badge names from badges.success?
          badge_names = ;
          $scope.availableTags = badge_names;
    });

    $scope.complete=function(){
    $( "#tags" ).autocomplete({
      source: $scope.availableTags
    });
    } 
  });
  </script>
  </head>

  <body ng-app="app" ng-controller="ctrl">
    <div class="ui-widget">
      <label for="tags">Tags: </label>
      <input id="tags" ng-keyup="complete()"/>
    </div>
  </body>

</html>

Answer №1

Take a look at this plunk for a simple solution: http://plnkr.co/edit/IgPyrCdFqT1pn53PIqSc. It's easy to understand, but there may be more efficient ways to accomplish the same task. Here's the code snippet:

Javascript

<script>
  var app = angular.module('app', []);

  app.factory('badges', ['$http', function($http) {
      return $http.get('https://api.stackexchange.com/2.2/badges?page=1&order=desc&sort=rank&site=stackoverflow')
        .success(function(data) {
          return data;
        })
        .error(function(err) {
          return err;
        });
  }]);

  app.controller('ctrl', ['$scope', 'badges', function($scope, badges){

      badgeNames = [];
      badges.then(function(response){

        for(var i=0; i < response.data.items.length; i++){
          badgeNames[i] = response.data.items[i].name;
        }

      });

      $scope.availableTags = badgeNames;
      $scope.complete = function () {
        console.log('running');
        $( "#tags" ).autocomplete({
          source: $scope.availableTags
        });
      };
}]);

HTML

<body ng-app="app" ng-controller="ctrl">
    <div class="ui-widget">
        <label for="tags">Tags: </label>
        <input id="tags" ng-keyup="complete()"/>
    </div>
</body>

In the code above, I extract badge names from JSON directly instead of utilizing API filters. In future, using filters in the Stack Overflow API would be more efficient.

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 show multiple markers using react-google-maps?

Can anyone help me figure out how to display multiple markers using the react-google-maps npm package? I've been following a demo that shows how to display one map marker, but when I try to add a second marker element, it doesn't show up on the m ...

Update the URL routing in angularjs to point to a new controller

Within the VisualisationController, I have come across this Angular code snippet: $http.get('api/apinetwork/getnetwork').success [...] The issue lies in the fact that it is trying to access instead of . How would you suggest adjusting the UR ...

Are your divs getting truncated?

Currently faced with a perplexing issue where inserting elements into a div causes scaling problems, resulting in most of the divs being cut off. This glitch occurs when two new elements are added. Despite changing page sizes and thoroughly debugging by o ...

Perform an Ajax request with JQuery in an HTML document and transfer the response to a different HTML page

This is my first attempt at using AJAX and jQuery to retrieve data from another HTML page. Below is the code I have written: Here is my JavaScript code: <script type="text/javascript> $(document).ready(function() { $('#submit').click( ...

How can I create a placeholder in semantic-ui components?

I'm currently utilizing the plugin and facing an issue with displaying the placeholder. Although data retrieval from the database is functioning properly, the placeholder is not being shown. Note:- When I remove the PHP code, the placeholder display ...

Algorithmically alter the view of the webvr camera

I am looking to dynamically change the position of a view within a webvr scene. My approach involves using the position.add method. Below is the code snippet that demonstrates how I programmatically move the camera: <a-entity position="33 0 -33" rota ...

Using Joomla to generate JSON data for AJAX requests

I encountered an issue while working on creating components with Joomla. The problem I faced is related to printing labels on Yandex map through objectManager, which requires retrieving data from the site in JSON format. To test this, I quickly created v ...

How can I display the output from Geocoder in a text box using the ArcGIS JavaScript API?

I am trying to customize the Geocoder text box in the ArcGIS JavaScript API by overriding the default search result. Although I have written some code for this purpose, I am not satisfied with the results. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...

Error in node.js framework due to memory allocation issue

Hello, I'm encountering an issue while running my JavaScript program. I keep getting a memory error. Can anyone help me identify the exact problem? <--- Last few GCs ---> [12908:0000015EB93DE800] 29162 ms: Mark-sweep 1396.7 (1425.2) -> 1 ...

Implementing two-dimensional orientation on particles in three.js

My first attempt at using three.js involves a basic particle animation with 4 different textures mapped onto them. Everything is working smoothly so far, except for one issue - I can't seem to rotate the particles randomly for different orientations ( ...

What is the process of importing an IIFE-based JavaScript module into an Angular TypeScript application?

I have come across a third-party SDK that is structured as an oldschool IIFE based module. The code looks something like this: var ThirdPartySDK = (function() { var export = {}; // Adding some methods to export return export; })(); To use this SD ...

Creating fresh paths in ReactJS

Is it possible to implement new routes in react JS with the current code provided below? I am looking for a way to create a route that does not need authentication. ReactDOM.render( <Provider store={store}> <PersistGate loading={null} ...

Issue with OnChange Not Triggering

Why isn't the onchange property firing when typing in my textbox? Check out the code below: VB.NET Dim textBoxUrlYoutube As New TextBox divUrlTextBoxContainer.Controls.Add(textBoxUrlYoutube) textBoxUrlYoutube.CssClass = "textboxyo ...

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

"Pressing the 'back' button on your browser takes

Is there a way to navigate back to the main page by clicking on an image? After selecting First, Picture1 will be shown. How can I go back to the selection page for further choices? <a href="picture1.jpg"> <h3>First</h3></a> <a ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

What is the best way to establish personalized CSS styles specific to each subdomain?

I am in the process of establishing a multi-tenant application with a single instance and single database setup. The backend infrastructure is built using Ruby on Rails, while the frontend is handled by a separate AngularJS app integrated with a Rails fram ...

Retrieve the object from the data received from the HTTP GET API call

I have a question that has been asked before, but I am unable to achieve the desired result with my current approach. When my service retrieves data from an API, it returns results in the following format: { "nhits": 581, "paramete ...

Utilize React to update the state of arrays in functional components

Need help with updating the cars array in my React app. When I click on the Add button, a new object is added to the updatedCars array but the state of cars does not get updated. Even after adding a new object to the array, the initial state remains uncha ...

"Transitioning from jQuery to Vanilla Javascript: Mastering Scroll Animations

I'm seeking guidance on how to convert this jQuery code into pure Javascript. $('.revealedBox').each(function() { if ($(window).scrollTop() + $(window).height() > $(this).offset().top + $(this).outerHeight()) { $(this).addCla ...