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

A guide to testing window.pageYoffset in webdriverIO using chai assertions

When conducting a selenium test using WebDriverIO and Chai, I encountered the need to capture the position of window.pageYoffset. Unfortunately, I was unable to find a direct way to do this in WebDriverIO. My initial attempts involved: browser.scroll(0, 2 ...

Attempting to manipulate information within the @click event handler embedded within a v-for loop

I am using a v-for loop to select dialog boxes that I want to open. <v-card @click="page.model = true"> In this code, page.model is being used as the v-model for a v-dialog component. data() { return { dialog1: false, dia ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

the conditional operator used without assigning the result to a variable

Exploring conditional operators on html canvas, I am seeking a streamlined approach to dynamically change stroke color based on conditions. Online examples have not provided a satisfactory solution in a single line of code. Currently, without using a cond ...

Trigger an AngularJS function when loading an HTML tag

Trying to execute an angular js function using a controller with the following code: index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DevPortal</title> <script src="js/angular.min.j ...

ng-disabled with function that activates on change

I am attempting to create a submit validation button that will only enable when all fields have been entered correctly. Due to the complexity of the validation process, I am unable to rely solely on formName.$invalid and need to write a custom function for ...

Using AngularJS $http.get method returns JSON with numeric keys, but we actually do not want any keys

Currently, I am conducting local testing on an AngularJS website. The issue I am facing involves parsing JSON data using the $http.get method from a local JSON file. When I manually define the JSON within my controller, everything works smoothly. However, ...

Angular JS effectively prevents redundant data from being displayed to users when scrolling infinitely while also efficiently removing DOM elements for previous data

I'm currently working on implementing AngularJS Infinite Scroll without using jQuery. My goal is to display the first 3 data items when the page loads and then load the next 3 data items from a JSON array object as the user scrolls. The issue I am fac ...

Styling for older versions of Internet Explorer (IE10 and earlier)

Could it be true that IE 10, 9, and others no longer support conditional statements? Is it also accurate to say that JQuery does not support the browser object above version 1.9? I am facing an issue with CSS rendering differently in Chrome and IE. A Goog ...

Can a single node_module folder be shared across multiple projects within a repository?

Imagine we have a central repository named REPO containing multiple grunt projects. Now, let's say we want to structure it like this: ROOT -- bower_components -- node_modules -- project_1 -- project_2 -- project_3 etc The current issue is that I nee ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Show information - press the button on the current PHP page

After successfully reading files via PHP from a directory and dynamically creating a drop-down menu to view the file content, I have a query. Is there a way to display the text files' content on the same page without calling another PHP page? I know t ...

Hide the grid menu item in the UI grid (specifically the export button, not all menu items

I have integrated angular ui-grid into my project and added an external button to export data as a csv file. The grid menu I am currently using is displayed below: My goal is to eliminate the export buttons from the grid menu, while keeping the columns i ...

What is the best way to retain selection while clicking on another item using jQuery?

There is a specific issue I am facing with text selection on the page. When I apply this code snippet, the selected text does not get de-selected even after clicking .container: jQuery('.container').on("mousedown", function(){ jQuery('. ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

I am puzzled as to why my DataGrid MUI component is not functioning properly

I am taking my first steps with MUI, the MaterialUI React Component library. After following the installation instructions in the documentation, I am now attempting to integrate the DataGrid component into my React project. My goal is to replicate the fir ...

To add additional nested data to a JSON object in JavaScript, you can use the push method or update

Looking to enhance the nested object data within my existing object The current structure of the JSON object array resembles this: var orderDetails = [{ "utilityType": "Electric", "firstName": "ROBERT", "lastName": "GUERRERO", "utilityList": [{ ...

Show a success message, clear the post data, and redirect back to the current page

I have a single web page with a contact form. When the form is submitted, I want it to redirect to the same page and display a success message that fades out after a few seconds. Additionally, I want the post data of the form to be cleared. The form also i ...

Exploring the functionalities of class methods within an Angular export function

Is it possible to utilize a method from an exported function defined in a class file? export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: AzureService.getConfiguration(), <-------- Com ...

What is the best way to continuously execute the 'onclick' function using AJAX inside a specific ID?

My challenge involves implementing a new AJAX upload feature to insert a data element from the onClick event in multiple rows. The issue I am facing is that it works fine for the first row, but when I add subsequent rows, the function no longer works upon ...