Send the typeahead object result from Angular to another function within the controller

In my current setup, I am utilizing the ui-bootstrap typeahead feature to fetch an object from an external API. Upon selecting the object, it triggers a callback function that stores the results in a separate function within my controller.

The challenge lies in wanting to take those results and send them to another API using an existing click function. My main query is how to pass the typeahead results into the click function for posting. The user interaction flow is outlined as follows:

<div>
    <input type="text" placeholder="Find A Game" 
           typeahead-on-select="setGames($item)" 
           ng-model="asyncSelected" 
           typeahead="test.name for test in getGames($viewValue)" 
           typeahead-loading="loadingLocations" typeahead-min-length="3" 
           typeahead-wait-ms="500" typeahead-select-on-blur="true" 
           typeahead-no-results="noResults">
</div>


<div ng-show="noResults">
  No Results Found
</div>
<button ng-disabled="!asyncSelected.length" 
        ng-click="addtodb(asyncSelected)">Add To Database</button>

As depicted, the label displays the item's name successfully. After the user selects the name, I utilize typeahead-on-select="setGames($item)" to send the entire object to its dedicated function. Subsequently, I intend to pass this object to another function inside the button tags using ng-click. Currently, it only passes the model, but ideally, I aim to send the entire $item object from the selection event. At present, my controller script appears like this:

angular.module('2o2pNgApp')
  .controller('GiantCtrl', function ($scope, $http, TermFactory, $window, SaveFactory) {

      $scope.getGames = function(val) {
        return $http.jsonp('http://www.example.com/api/search/?resources=game&api_key=s&format=jsonp&limit=5&json_callback=JSON_CALLBACK', {
          params: {
            query:  val
          }
        }).then(function(response){
          return response.data.results.map(function(item){
            return item;
          });
        });
      };

      $scope.setGames = function (site) {
        var newsite = site;
      };


      $scope.addtodb = function (asyncSelected, newsite) {
            TermFactory.get({name: asyncSelected}, function(data){
              var results = data.list;
              if (results === undefined || results.length === 0) {
          SaveFactory.save({vocabulary:'5', name:newsite.name, field_game_id:newsite.id}, function(data) {
              $window.alert('All Set, we saved '+asyncSelected+' into our database for you!')
          });
              } else {
                // do stuff
            });
      }

  });

Despite numerous attempts, I have been unable to pass the complete $item object into this click function to effectively post all the necessary information.

Answer №1

According to a New Developer's Comment:

The $item variable is restricted to local availability for typeahead-on-select functionality. To resolve this issue, you can either assign it to a model within your controller or set the model of the typeahead to be the item itself: typeahead="test as test.name for test in getGames($viewValue)" – New Developer

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

playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects. After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly. My query pertai ...

Minimize a collection of JavaScript objects

I am working with an Array of objects where I need to return the collection as an Object, with the key names being the indexes of their length. Additionally, I have to filter this object based on its values. Check out my code snippet below: const data = ...

Creating a personalized class in Google Apps Script: a step-by-step guide

I'm trying to define a new class within my Google Apps Script. Even though the language is based on JavaScript, I encountered an issue while using an example from a JavaScript manual: class Polygon { constructor(height, width) { this.height = ...

Angular directive using ng-if to display image

I have the following code in my showCtrl: $scope.showTeam = function(){ var count = 0; for (var k in subordinates) { if (subordinates.hasOwnProperty(k)) { ++count; } } if(count > 0){ r ...

How can I specify the exact width for Bootstrap 3 Progress Bars?

I have a single page that displays all my files in a table format, and I also have the count of open and closed files. My goal is to represent the percentage of closed files using a progress bar. The width of the progress bar should change based on this p ...

Dealing with jQuery hover/toggle state conflicts in Internet Explorer?

Check out my code snippet: <!doctype html> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <style type="text/css"> label {display:block; w ...

Accessing dropdown selection in Javascript-Json: A Comprehensive Guide

My dropdown list is being populated dynamically using json. The selected option from the first dropdown determines the options in a secondary dropdown. I need to use the selection from the second dropdown to automatically fill out two more fields. For exa ...

Observing Node.js processes to track the peak memory usage of each process

Is there existing monitoring software that can track newly spawned node.js processes on my machine and display the maximum memory usage when the process ends? If not, how can this be achieved effectively? I have identified the specific Node.js processes I ...

Another option instead of using ng-repeat when scope is not required

Currently, I am facing a problem where Angular is generating a large number of rows and columns, resulting in poor performance! I suspect that the issue lies with ng-repeat creating a new scope for each element it generates. However, since my function doe ...

Is there a way to generate a button that displays the subsequent 5 outcomes from the database without navigating away from the current

I am looking to implement a button on my webpage that, once clicked, will load the next set of five questions from my database. I prefer not to use pagination or the GET method to prevent users from navigating back to previously answered questions. My goa ...

What are the methods for differentiating between a deliberate user click and a click triggered by JavaScript?

Social media platforms like Facebook and Twitter offer buttons such as Like and Follow to allow users to easily engage with content. For example, on Mashable.com, there is a Follow button that, when clicked, automatically makes the user follow Mashable&ap ...

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

Encasing newly inserted child components within my designated slot

If I have a component with a single slot and instead of simply rendering all its children, I want to wrap each element individually, the following approach can be taken: Vue.component('MyElement', { render: function(createElement){ for (l ...

Attempting to transfer a JSON object from a frontend Form Input to an Express backend

Apologies for bringing up what may seem like a basic issue, but I've been searching extensively (even through axios' documentation) and haven't been able to pinpoint exactly what I need to resolve this issue. I have created a simple To-Do we ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

The submit option fails to appear on the screen in the JsonForm library

I've been using the JsonForm library ( https://github.com/jsonform/jsonform ) to define a form in HTML. I have set up the schema and form of the JsonForm structure, but for some reason, the "onSubmit" function that should enable the send button is not ...

Error message: Unable to access properties of null when calling 'registerPlugin' in @devexpress/dx-react-grid-material-ui

I have developed a CustomGrid component that is based on the DevExpress Grid component. So far, it has been working smoothly. Here's how the implementation looks like in App.tsx: import Paper from "@mui/material/Paper"; import { Table, TableHeaderRow ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

Discovering the following element containing an ID attribute with jQuery

Upon clicking a link, my goal is to locate the subsequent <section> with an ID attribute and retrieve its ID. In the provided code snippet and JavaScript function, the expected outcome upon clicking the link is for "section_3" to be logged in the co ...

ReactJS is unable to locate a valid DOM element within the target container

I recently embarked on my journey to learn ReactJS and I celebrated successfully writing my first code. However, when I encountered the same pattern with components, an error popped up stating _Invariant Violation: registerComponent(...): Target container ...