Troubleshooting: AngularJS live search API not updating upon ng-model modification

As a newcomer to Angular, I find myself struggling to navigate the learning curve.

Currently, I am completing a FreeCodeCamp Zipline project to create a Wikipedia search application. One of the key features required is a live search with suggestions for article titles. Unfortunately, I have been unable to get this functionality to work.

I have developed a factory to handle the Wikipedia API call. However, the factory only works once and does not update when changes are made to the search field. It seems that the factory is not being triggered when modifications are made to the input field, despite my attempts to resolve the issue.

HTML

<section id="container" ng-app="wikiSearch" ng-controller="searchPanel" class="center">
  <h1>Wikipedia Viewer</h1>
  <input id="search" type="text" placeholder="search" ng-model="searchTerm" ng-model-options="{debounce: 300}"/>
  <section id="results"><a href="#" target="_blank" class="wiki-entry"> </a>
    <!-- test code-->
    <div>{{searchTerm}}</div>
    <div>{{titleSearch}}</div>
  </section>
</section>

Javascript

var app = angular.module('wikiSearch', []);

app.controller('searchPanel', [ '$scope', 'API', function ($scope, API) {
  $scope.searchTerm = 'einstein';
  $scope.titleSearch = {};
  $scope.searchResults = {};

  var api_base = "https://en.wikipedia.org/w/api.php?";
  var fullParams = "format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=30&prop=extracts&exintro&explaintext&exsentences=2&exlimit=max&gsrsearch="
  //var titles = "format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=8&gsrsearch="
  var callback = "&callback=JSON_CALLBACK"

  API.search(api_base + fullParams + $scope.searchTerm + callback).success(function (data) {
    $scope.titleSearch = data;
  });

}]);


app.factory('API', [ '$http', function ($http) {
  return {
    search: function(targetUrl) {
      console.log(targetUrl);
      return $http.jsonp(targetUrl);
    }
  }
}]);

To view the original Codepen project and further analyze the issue, click here: Codepen Project

It's apparent that any alterations to the search field do not reflect any changes in the returned JSON data. The factory is called only once.

While I lack a deep understanding of how Angular functions, I had assumed that the factory would update in the scope with each modification to the input field. Clearly, my assumption was incorrect. I would appreciate insights on why this occurs and guidance on how to rectify it.

Answer №1

Your code is experiencing an issue because you are not triggering the API call when the search input changes. Make sure to listen for the change event on your text field and then execute the API call as shown below.

HTML

<input id="search" type="text" ng-change="update()" placeholder="search"
  ng-model="searchTerm" ng-model-options="{debounce: 300}" />

Controller

$scope.update = function(){

   API.search(api_base + fullParams + $scope.searchTerm +callback)
      .success(function (data) {
         $scope.titleSearch = data;
      });

}

Check out the updated version of your CodePen here with the modifications mentioned above.

Answer №2

To ensure the search field is constantly monitored for changes, it is recommended to implement an event listener. One option is to utilize ngChange.

jade

input#search(type='text' placeholder = "search" ng-model="searchTerm" ng-change='search()' ng-model-options="{debounce: 300}")

JS

     $scope.search = function () {
  API.search(api_base + fullParams + $scope.searchTerm + callback).success(function (data) {
    $scope.titleSearch.data = data;
    console.log($scope.titleSearch);
  });
 }

 $scope.search()

View the functionality in action on codepen

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

The data in AngularJS is not being successfully incorporated into the service

Utilizing angularjs and ajax, I am attempting to retrieve data from a webservice and pass it to the controller. To accomplish this, I am using a holder (a factory method or service). The setup works fine without the webservice, but when trying to fetch dat ...

Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this : <div class="col-md-4"> <div class="form-group"> <label class="control-label col-md-3">Location</label> <div class="col-md-9"> <?php ...

Object placed at the mouse position is shifted from its original location

I am working with ThreeJS in conjunction with MindAR, attempting to position an object where I click on the screen using my mouse. const mousePositionX = (e.clientX / window.innerWidth) * 2 - 1; const mousePositionY = -(e.clientY / window.innerHeight) * 2 ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

An element featuring a background color is vertically aligned in the middle of its parent container

Struggling to achieve a seemingly simple task, but coming up short on finding a solution. The goal is to have a background-color that aligns vertically in the middle of the first and last images in a stack of images. It may sound more complicated than it a ...

mention the element to display on the pagination

I find the logic here quite puzzling. This particular code block seems to be related to pagination, as it involves a function that is triggered upon clicking. componentDidUpdate() { const { location } = this.context; const { query } = this; if ...

Images on web pages are automatically resized to fit into a smaller preview window

Currently, I am facing an issue with the display of images in my grid windows on my website . The images are appearing as partial representations instead of rescaled versions where the whole picture is resized to fit the grid window. I have attempted mod ...

The potential issue of undefined objects in TypeScript when utilizing computed properties in Vue3

https://i.sstatic.net/I5ZVO.png I've attempted adding a ? after each word and also experimented with the following code: const totalNameLenght = computed(() => { if (userFirstnameLenght.value && userLastnameLenght.value){ ret ...

To ensure font-weight is applied to innerHTML text on Laravel, it must be styled with a white color for the changes to take

I have added a countdown feature to my Laravel 5 application and I am trying to adjust the font weight of the text, but I am facing some difficulties. When I set the color to #fff, the font-weight works perfectly fine, but when I change the color, the font ...

Transferring information between HTML pages using JSON and jQuery

After reviewing the topics, I was unable to find a complete answer. My objective is to populate a drop-down menu with text from another HTML file. Both HTML files are located on localhost. It is mandatory for the data to be in JSON format. Initially, I a ...

September always seems to throw my Date list off course, skipping a month and causing it to vanish without a trace

The issue at hand I have been working on developing an Open-Source Vue Application that features a Gantt Chart for visualizing tasks along a timeline. Users are able to customize the date range, with the default setting to display the current and upcoming ...

Obtaining information from python script with 'child-process' functions successfully in a regular node.js script, yet encounters issues in a script that is being imported

I'm currently developing a node.js application that involves sending data to a python script for calculations, and then receiving the processed data back in a discord.js command-script command.js, which is executed from the main script index.js. To se ...

Substitute the specific class title with the present class

Here is a sample class (supposed to be immutable): class A { normalMethod1(): A{ const instance = this.staticMethod1(); return instance; } static staticMethod1: A(){ return new this(); } } The code above works fine, but how can I re ...

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. https://i.sstatic.net/eLSto.png I made an attempt at achievin ...

Tips for designing a unique CSS ellipse effect for text styling

Hey there! I have a list of titles in a drop-down menu as strings, for example: "Bharat Untitled offer #564", "Bharat Untitled offer #563" The titles are quite long, so we want to display the first eight characters, followed by '...' and then ...

Displaying two arrays using ng-repeat leads to an error

In my attempt to create a table using two arrays in AngularJS, one containing Employees' names and the other containing Services' names, I encountered an error: Error: [ngRepeat:dupes] Below is my AngularJS code: var model = angular.modul ...

I have an npm package that relies on X (let's say material-ui). What is the best way to prevent users from having to install

Hey everyone, I recently released an npm package called X that relies on material-ui as a dependency. While many users of X already have material-ui installed, there are some who do not. How can I ensure that those who have material-ui installed continue t ...

What is the best way to pause execution until receiving an API response in a separate function?

Seeking guidance as a newcomer to JavaScript/NodeJS, I am struggling to grasp the concept behind a function I am working on. The purpose of this function is to execute an action based on the response received from an API post request within a separate func ...

In AngularJS, be sure to remove any previous growls before displaying a new one

Working on growl.info() using angularjs and have a query. How can I check if there is already a growl displayed on the screen before adding a new one? The requirement is that when a new growl is triggered, the previous one should be removed from the view. ...

Store additional data with the visitor ID WEB in Fingerprint JS V3

After browsing through similar questions, I couldn't find a solution that fits my needs. Basically, I have a website where a random emoji is generated and stored in local storage. However, this method is not effective as users can easily delete their ...