Exploring the concept of ng-model with undefined values in AngularJS

Having an input with a $watch function that updates a search query in real time through AngularJS, I am encountering an issue. Despite setting the initial value of the model to empty, it automatically triggers the search and displays results.

My concern is how can I ensure that the search is triggered only when the user types something into the input field? I've attempted creating a function that activates the $watch on ng-click, but have had no success so far. I also tried using ng-init without luck. Perhaps implementing a condition within ng-repeat to only run if the name is not empty could work?

Do you have any ideas for a possible workaround?

Below is my JavaScript code:

function Ctrl($scope, $http) {
    var get_results = function(name) {
            $http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=30').
        success(function(data3) {
            $scope.results = data3.results;
        });
    }
    $scope.$watch('name', get_results, true);
    $scope.name = '';
}

Here's my HTML snippet:

<div ng-controller="Ctrl">
  <h1>Search Artist</h1>
  <input type="text" ng-model="name"/>
  <ul>
    <li ng-repeat="result in results">{{result.title}}</li>
  </ul>
</div>

If you want to view a working example, check out this JSFiddle.

I would greatly appreciate any assistance! Thank you, Eric

Answer №1

To ensure the name is not empty before making a request, use an if condition within the get_results function.

var get_results = function(name) {
  if (name) {
    $http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=30').
       success(function(data3) {
         $scope.results = data3.results;
    });
  }
}

JSFiddle

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

Shaky parallax movement

I recently created a website with a parallax effect, but I'm experiencing some performance issues with jittery movement. The page uses CSS3 transform scale to zoom in and out, and automatically resizes on page resize with JavaScript/jQuery. For the ...

Tips to prevent redundancy in a one-line 'if' statement in JavaScript

While working on a piece of code, I came across something bothersome and couldn't find a solution even after doing some research. It's functional, but it feels redundant to have to type this.className three times: this.className != 'selecte ...

Executing server-side method with jQuery in .Net 1.1

Currently, I am utilizing .net1.1 and attempting to invoke a server-side method using jQuery upon clicking the browser's Close button. However, my code does not seem to be functioning correctly. I have provided my code below for reference. Can anyone ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

Need help fixing my issue with the try-catch functionality in my calculator program

Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be a ...

Instructions for smoothly moving back to the top (or specific anchor) from the current view using AngularJS

As I prepare to delve into the world of Angular, a burning question comes to mind. Is it feasible to create an animation that scrolls up to the top of the page or a specific anchor point when transitioning to a new view after clicking a link while scroll ...

Enhancing Child Elements with CSS - Evaluating Rating Systems

Is there a way to change the opacity of certain images inside my div when hovering over them? Specifically, I want the 4th image and the first three to have an opacity value of 1. I've looked into using nth-child but am unsure how to implement it for ...

"Error: The property $notify is not found in the type" - Unable to utilize an npm package in Vue application

Currently integrating this npm package for notification functionalities in my Vue application. Despite following the setup instructions and adding necessary implementations in the main.ts, encountering an error message when attempting to utilize its featur ...

What might be causing res.download to retrieve a zip file that is empty?

Using expressjs for my app development, I have created a service to download files on the client side using res.download(filepath, filename). The following is the code snippet of my service: router.route('/downloadFile').get(function(req,res){ ...

Retrieve the text input from the text field and display it as

Is there a way to display what users enter in a textfield when their accounts are not "Activated"? Here's an example: if(active == NULL);{ //I've attempted the following methods. //In this scenario, 'username' is the name of ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...

The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this: data(){ return{ test: test_data, nodes:{}, edges:{}, nextNodeIndex: Number, selectedNodes: ref<st ...

The correct reading of JavaScript in HTML is a common source of confusion

After creating a basic application using the code provided in a forum thread and testing it on the worker sandbox MTurk site, I noticed a peculiar issue. The application runs smoothly when following the code from the forum answer directly. However, when at ...

React component slider encountering issue of 'undefined property style reading'

I attempted to develop a component for a slider, but it seems to be malfunctioning. Upon the initial rendering, I encountered the error: 'cannot read property style of undefined...' When I logged x[slideIndex-1], initially it returns undefined ...

An issue arose when attempting to access a Mashape web service with JavaScript

I am attempting to make use of a Mashape API with the help of AJAX and JavaScript. Within my HTML, I have a text area along with a button: <div> <textarea id="message" placeholder="Message"> </textarea> <br><br> ...

Every time I input information into the form, it keeps coming back as undefined

function displayProduct() { var product = document.getElementById("productForm"); var item = product.elements["item"].value ; document.getElementById("outputResult").innerHTML = item ; } <div> <p id="outputResult"></p> </di ...

Is it possible to execute a task following a particular Websocket.send() in JavaScript?

After sending a message to a websocket, I am trying to send a POST request using callbacks. I attempted the following approaches: socket.send(message,function(){...}); and function sendsocket(message, callback){ socket.send(message); callback; } and ca ...

Vue app showcasing array items through search upon button pressing

As I delve into learning Vue Js, I've encountered a bit of confusion. My goal is to showcase array elements from a Rest API based on the specific ID being searched for. For example: within my Json File are various individuals with unique IDs, and when ...

Retrieving information from a separate JavaScript file

I'm currently developing a Discord Bot and my code is all contained within one file. My goal now is to break this code up into multiple files for better organization. For instance, I plan to have: index.js which will handle all the requires (e.g. var ...