Set the ng-model attribute to "searchText" on an input within Angular JS, assigning it a value when a list item is clicked

Using angular.js (ng-model="searchText"), I have implemented a searchable list with an input field. When a list item is clicked, the content of the selected item can be displayed using {{selected | json}}. My goal is to set the value of the input to the selected element when a list item is clicked.

The objective is to create a custom autocomplete feature that continuously displays a list of options, filters the options as the user types, and populates the input field upon selection of an option.

HTML

<html ng-app> 
<section>
   <div id="content-body" class="container search-page"><!-- begin content-body -->
    <div id="content-frame" class="container"></div><!-- end content-frame -->
      <section>
        <div class="search-container">
          <div class="search-wrapper">
            <input type="search" class="input-from" autocomplete="off" placeholder="Search" ng-model="searchText" value="{{searchText}}">
          </div> 
        </div>
      </section>
      <section>
        <div ng-controller="ContentCtrl">
          <ul class="list-group search">
        <!--<li class="list-group-item group-title">
                <span class="icon itinerary-icon"></span>
                Popular Destinations
            </li>-->
              <a ng-click="setMaster(cities)" ng-repeat="city in cities | filter:searchText | limitTo:limit" href="#" class="list-group-item">{{city}}</a>
          </ul>
        </div>
      </section>
   </div><!-- end content-body -->
</html>    

JS

function ContentCtrl($scope, $http) {
    "use strict";

    $scope.url = '../mobile-site/cities.json';
    $scope.cities = [];
    $scope.limit = 10; // maximum of 10 cities loaded

    $scope.fetchContent = function() {
        $http.get($scope.url).then(function(response){
            $scope.cities = response.data.cities; 
        });
    }

    $scope.fetchContent(); // fetch cities list

    $scope.setMaster = function(city) {
            $scope.searchText = city; // get selected city using {{selected | json}}
        }
    } 

JSON

{
"version": "082B6AF45261B81358E8F99F0FAEC4A4",
"cities": [
"A Friela Maside, Spain",
"A Gudina, Spain",
"AHA, Germany",
"AL, Norway"
]
}

Answer №1

It seems that there are a few errors in the code snippet provided:

<div ng-model="chosen">
    <a ng-click="setMaster(cities)" ng-repeat="cities in cities | filter:searchText | limitTo:limit" href="#" class="list-group-item">{{cities}}</a>
</div>

The corrected version should look like this:

<div ng-repeat="city in cities | filter:searchText | limitTo:limit">
    <a ng-click="setMaster(city)" class="list-group-item">{{city}}</a>
</div>

Furthermore, it appears that the intended functionality is to set the master city based on user selection:

$scope.setMaster = function(city) {
    $scope.searchText = city;
}

Lastly, the purpose of using ng-model on a div element is unclear, as it is typically used for inputs, textareas, and selects. For more information, refer to this documentation.

To see a working example, you can check out this fiddle -> http://jsfiddle.net/weSpW/3/.

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

Deactivating Timeout Requests in Koa Server

I keep encountering a connection reset error. I strongly believe it's stemming from a lengthy REST request, causing it to timeout. { [Error: socket hang up] code: 'ECONNRESET' } Is there a method to deactivate request timeouts within Koa, ...

Steps to resolve the 'Unknown keyword' issue while packaging a CSS file using webpack

In the process of upgrading dependencies to the latest versions for my Electron app built in Angular, I have encountered some issues. ✅ Electron remains on v19 ✅ Tailwindcss is updated to v3.1.8 ⬆️ Angular is being upgraded from v11 to v14 ⬆️ ...

Make sure to always send back JSON data when using the default error handler in ExpressJS

I'm in the process of developing an API server using ExpressJS. I want to guarantee that the server consistently delivers JSON data rather than HTML data. While I can easily make the server respond with JSON for all customized routes, I encounter diff ...

Encountered an error when trying to access the 'modules' property of undefined in the /node_modules/bindings/bindings.js file while working with electron and setting up

1. npm install -g node-gyp 2. npm install serialport -S 3. npm install electron-rebuild -D 4. ./node_modules/.bin/electron-rebuild.cmd and after that, the rebuild process is completed. When I execute the command: npm run electron:serve, I encounter an ...

Error message: "Issue encountered with locating Node import module while operating within a docker

I've created a React app along with a Node.js server that includes the following imports: import express from 'express' import compression from 'compression' import cookieParser from 'cookie-parser' import bodyParser from ...

Issue with React and Material UI: The Textfield's "onChange" event is not being triggered

I have been attempting to trigger an onchange function when my Textfield is populated, but for some reason the function never seems to be activated. Despite seeing changes triggered by the React devtool plugin in Chrome, I am at a loss. Any suggestions? i ...

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...

Using Socket.io with NGINX has been quite a challenge as I have been struggling to properly configure the sockets

Having my backend set up with socket.io, I wanted to configure socket.io with nginx. Despite configuring nginx with the following settings, my routes other than sockets are functioning properly but my sockets are not working. server_name yourdomain.com ww ...

Trouble accessing state when React child calls parent method

Within my project, I am working with 3 components that are nested as follows: App->GameList->GameItem The App (parent) component has a method that is triggered by the onClick event within the GameItem (child) component Upon clicking the GameItem co ...

What are the steps to integrating D3js into a WordPress website?

After installing Wordpress and the d3js plugin, I'm looking for the most effective way to upload data in order to create and display graphs on my website. Should I directly upload csv files? And if so, where should I store them? If I prefer storing ...

Does the functionality of Protractor rely on a specific version of AngularJS?

Recently, I began exploring the world of Protractor. One burning question on my mind is its limitations and whether it relies heavily on a specific version of AngularJS. ...

Warning: The update depth in Nextjs has surpassed the maximum limit

I am currently developing a React Header component with a dropdown menu feature that can be toggled. Upon loading the page, I encountered the following error: next-dev.js?3515:20 Warning: Maximum update depth exceeded. This issue may arise when a compone ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

The key up event in JQuery does not seem to be triggered when selecting the second option in the Select2 plugin's multi

Encountered an issue with the select2 plugin while trying to change the option list based on user input for the second multiple option. The first time I enter text in the multi-select field, the keyup event is triggered and an ajax function is called to b ...

Values in Vuex do not get updated by getters

I'm having trouble understanding the functionality of getters in Vuex. The issue arises when I log out the token and find that the state and localStorage are empty, but the getters still contain the old token value. In the created lifecycle hook, I ha ...

How can I use jQuery to switch classes or activate a click event on the most recently clicked element?

Within my <ul></ul>, there are 4 <li> elements. <ul class="wcarchive-terms-list"> <li class="wcarchive-term wcarchive-term-parent woof_term_224"> <label class="wcarchive-term-label"> <span cla ...

Ways to substitute the v-model pattern with react hooks

Transitioning my application from Vue to React. In Vue 2, using v-model on a component was similar to passing a value prop and emitting an input event. To change the prop or event names to something different in Vue, a model option needed to be added to t ...

Executing requests asynchronously in AngularJS in a sequential manner

I have a need to run 3 requests concurrently. Here is the current code I am using: for (var url in urls){ console.log('queued!'); $http.jsonp(url, {timeout: 10000}).then(function (response, status, headers, config) { if (resp ...

Designating a certain function to a designated button

On my page, I have three different forms with submit buttons in each. There is a code that is supposed to change the value of a button in a specific form when clicked. However, whenever I click on any submit button, all the values in the buttons of the v ...

Error: Angular7 Unable to locate namespace 'google'

I am currently utilizing the import { MapsAPILoader } from '@agm/core'; package to enable auto-complete address search functionality. However, I have encountered an error message stating cannot find namespace 'google'. The error occu ...