Angular/Ionic - How can I prevent my function from being called repeatedly while typing in an input field?

I am currently in the process of self-teaching how to construct an Angular/Ionic application. To store JSON, I am utilizing Backand and aiming to retrieve a random JSON value each time the page is refreshed.

An issue I am facing is that the random call function triggers every time I input text. The reason for this behavior eludes me.

index.html

<label class="item-input-wrapper">
        <input type="text" placeholder="New Todo" ng-model="input.name">
</label>
<div>
  <p class="challenge-text">
       {{challenges[randomChallenge(challenges.length)].name}}
  </p>
</div>

app.js

    .controller('AppCtrl', function($scope, ViewChallenges) {
  $scope.challenges = [];
  $scope.suggested = [];
  $scope.input={};
  $scope.randomChallenge = function(length){
    return Math.floor(Math.random() * length);
}

  function getAllChallenges() {
    ViewChallenges.getChallenges()
    .then(function (result) {
      $scope.challenges = result.data.data;
    });
  }

  $scope.suggestChallenge = function(){
      ViewChallenges.suggestChallenge($scope.input)
      .then(function(result){
          $scope.input = {};
          getAllChallenges();
      })
  }



  getAllChallenges();

})

.service('ViewChallenges', function ($http, Backand) {
  var baseUrl = '/1/objects/';
  var challenges = 'challenges/';
  var suggestedChallenge = 'suggested/'

  function getUrl(x) {
    return Backand.getApiUrl() + baseUrl + x;
  };


  getChallenges = function () {
    return $http.get(getUrl(challenges));
  };

  suggestChallenge = function(suggested){
      return $http.post(getUrl(suggestedChallenge), suggested)
  }


  return {
    getChallenges: getChallenges,
    suggestChallenge: suggestChallenge
  }
});

Answer №1

The reason behind this behavior is that the value of input.name keeps on changing every time you make a modification to the input.

As a result, the function

randomChallenge(challenges.length)
is impacted by these changes.

Hence, with each alteration in the input, the outcome of

{{challenges[randomChallenge(challenges.length)].name}}
will also fluctuate accordingly.

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

Utilizing the power of Vue Router with DataTables

I am currently facing an issue where I want to include links or buttons in my DataTable rows that can navigate to a vue route when clicked. The straightforward approach would be to add a normal <a> element with the href attribute set to "/item/$ ...

transferring information between GWT web application and App Engine backend (Java)

I am currently building a client with GWT and a server using App Engine. Our setup includes a mix of standard servlets and Restlet components. After following some guidance online, I have successfully utilized restyGWT on the client side for encoding and ...

Can anyone explain why the Splice function is removing the element at index 1 instead of index 0 as I specified?

selectedItems= [5,47] if(this.selectedItems.length > 1) { this.selectedItems= this.selectedItems.splice(0,1); } I am attempting to remove the element at index 0 which is 5 but unexpectedly it deletes the element at index ...

AngularJS DOM modification completion event

After writing some AngularJS code that swiftly sets up scope fields, I noticed that both AngularJS and Chrome took a considerable amount of time to generate and display the DOM. The main culprit seemed to be a handful of ng-repeat bindings to lengthy lists ...

Creating a PEG Grammar that can match either a space-separated or comma-separated list

I am currently working on creating a basic PEG (pegjs) grammar to analyze either a space separated list or a comma separated list of numbers. However, it seems like I am overlooking a crucial element in my implementation. Essentially, I aim to identify pat ...

Passing objects to an AngularJS form using UIB TypeAhead without two-way binding

In my current situation, I am encountering an issue with a typeahead feature on a repeating form element that consists of 5 input fields. While everything functions correctly when selecting results and populating the input fields, the model does not get up ...

Special function to handle ajax requests malfunctioning

I am seeking to develop a unique function for AJAX post requests. Below is the existing source code: function handleAjax(url, data) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.st ...

Converting an array to a JSON object using JavaScript

I need help with converting the following array into a JSON object: var input = [ 'animal/mammal/dog', 'animal/mammal/cat/tiger', 'animal/mammal/cat/lion', 'animal/mammal/elephant', 'animal/ ...

AJAX allows developers to declare variables within their code to

Here is a snippet of my JavaScript code: $(\"img.agree\").click(function() { var follow_id = $(this).attr(\"id\"); var user_id = $(\"img.user_id\").attr(\"id\"); $.ajax({ type: \"POST& ...

creating a personalized dropdown menu with react javascript

Is it possible to create a chip in a single select dropdown in React? In a multi-select dropdown, a chip is created as shown in the example below. Can we achieve the same effect in a single selection dropdown? const DropdownExampleClearableMultiple = () = ...

What's up with the Chrome Dev Tools Error Log?

I am having an issue with debugging JavaScript files using breakpoints in Chrome Dev Tools. Whenever an error occurs, a red error message flashes on the screen so quickly that I can't read what it says. Is there a way to change this setting or access ...

The datepicker is functioning correctly, however, the displayed value does not reflect the updated date

The version of angularjs being used is 1.5.11. Within my .NET MVC project, the bs-datepicker element from angularjs is incorporated. Featured below is the datepicker component accompanied by a pair of images functioning as buttons within my application: & ...

Is it possible to utilize $(this) within the $.post() function?

I seem to be having trouble accessing $(this) from inside the $.post section. It works perfectly fine outside of it. Here is the JavaScript code: $('.idea').each(function(){ var title = $(this).html(); $.post("votes.php", { t ...

What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below: let s: string = new String("foo"); // ERROR let S: String = "foo"; // OK It's interesting to ...

How about a custom-designed talking JavaScript pop-up?

Looking to customize the appearance (CSS, buttons...) of a "confirm" JavaScript dialog box while ensuring it remains persistent. The dialog box appears after a countdown, so it is crucial that it maintains focus even if the user is on another browser tab o ...

Navigating through different views in a Vue application using Vue Router directly from Vuex actions

Currently, I am in the process of developing a web application using Vue 2.x and Vuex 2.x. In this project, I need to retrieve some data from an external source via an http call. If this call fails, my objective is to redirect to a different page. GET_PET ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...

What could be causing my Chrome extension to function on Mac but not on a PC?

I created a basic Chrome extension that includes a background page with the following code: <script type="text/javascript> chrome.tabs.onDetached.addListener(function(tabId, info){ var id = tabId; chrome.tabs.get(id, function(tab) { ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

Is it possible to maintain the sidebar while eliminating the scrolling JavaScript?

Looking to recreate the image display style on Facebook where pictures appear in a lightbox format. The challenge I'm facing is figuring out how they manage to have the sidebar with no visible scroll bar inside... If you want to see this for yourself ...