Troubleshooting issues with multiple $scope.$watch functions in AngularJS

I'm having an issue where only the first $watch function is firing in the same controller. Both inputs have ng-model assigned to them. Can someone help me understand why this is happening? (appreciate any help)

$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});


$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});

Answer №1

Experiment with this code snippet and observe the output in your console:

$scope.$watch('id', function(newVal, oldVal) {
    console.log(oldVal, newVal);
});

If the logging is functioning correctly, why not take a shot with the newVal variable like this:

$scope.$watch('id', function(newVal, oldVal) {
    if (newVal !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+newVal+".*'}}";
        fetch2(filter);
    };
});

Adjusted version

Answer №2

//Give this a shot
var deregisterWatchGroup = $scope.$watchGroup(['firstModel', 'secondModel'], function (newValues, oldValues) {
         console.log(newValues[0], oldValues[0]); //for the first model 
         console.log(newValues[1], oldValues[1]); //for the second model 
         // handle your tasks here
 });
  //stop watching
 $scope.$on('$destroy', deregisterWatchGroup);

Answer №3

If you want to monitor several variables within the same controller, you can achieve this by:

$scope.$watchGroup(['username', 'email'], function(updatedValues, previousValues) {

 updatedValues[0] -> $scope.username 
 updatedValues[1] -> $scope.email 

// Proceed with your tasks.

});

Answer №4

Many thanks to everyone. I figured out the problem with my html rendering of the results, and it turns out the main reason behind it was my own mistake. I had mistakenly included an unnecessary ng-show element that was causing the results to be hidden.

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

Is it possible for an Ajax/jQuery script to display multiple dependent dropdown box options within a single Form URL?

In the process of developing a basic form prototype that includes 4 entries in PythonAnywhere (Python 3.7 + Django): PinID (Independent, simple manual number entry) Region (Independent Dropdown Box) Name (Region-Dependent Dropdown Box) Source (Name-Depen ...

Is there a Rust secp256k1 alternative to the `crypto::ECDH::computeSecret()` function in NodeJS?

After developing a functional NodeJS/Javascript function, I am now intrigued by the idea of achieving similar results using the Rust secp256k1 library: /* * Calculate the Symmetric Key from the Public and Secret keys from two * different key pairs. * ...

Showing undefined or null values in React and JavaScript

My goal is to format undefined or null values by italicizing them. If the value is an empty string, it should be displayed as is. If it has a value, that value should also be displayed as is. However, I am encountering an issue where null or undefined val ...

Is it necessary to have asynchronous WEB API's when using AngularJS's promise defer implementation?

Is it necessary to expose async methods through WEB-API if Angular JS already supports Promise Defer functionality, which is asynchronous on the client side? ...

Storybook encounters an undefined error with the Vuex store

Here is a snippet from my main.js file: import './plugins'; import store from './store'; import FileUpload from './components/FileUpload'; export default { install(Vue) { Vue.component('file-upload', ...

Issues with looping in Internet Explorer 8

Hey, I'm having an issue with this JavaScript function: function test(){ var count = 0; var date1 = $('#alternatestartdate').val(); var date2 = $('#alternateenddate').val(); ...

React Redux components are failing to render after changes are made to the state array

I'm fairly new to using React, Redux, and Thunk in my project. Right now, I'm facing an issue where I fetch an array from an API call in my action/reducer, but it doesn't re-render in the connected component/container that's hooked up t ...

Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I&apo ...

AngularJS - FormController inaccessible to dynamic forms

It is important to consider that one customer may have multiple contact information. To create a user-friendly HTML form, I have utilized a structure similar to the following: <div> <customer-form/> <!-- single <form> element ...

Is there any importance to port 9229 and is it possible to modify it?

In my initial training, it was always recommended to run a local Node server on port 3000. However, after learning about the Chrome Node debugger in a tutorial that uses port 9229, I decided to switch to this port. For more information on port 3000, you ...

Error message: The "spawn" function is not defined and is causing a TypeError to be thrown in

Having a bit of trouble here. I'm trying to make an async request using redux-thunk in my action creator, and the code looks like this: export const downloadFromYoutube = (download) => { console.log("Hello"); return dispatch => { va ...

Restricting the number of characters allowed for text messages and keeping track of the count

I am attempting to implement a character limiter for an html textarea using JavaScript. Additionally, I want to include a total character counter. Unfortunately, the code I have written isn't functioning as expected. Can anyone identify where my mist ...

Transferring variables between PHP pages seamlessly without the need for refreshing the page

I have a situation involving two pages. The first page, named mainform.php, contains a form where users input test results that are then stored in a database upon submission. Within mainform.php, there is a Jira issue slider tab where users can report any ...

Jquery for controlling the navigation menu

I'm new to JavaScript and facing 3 challenges: 1. When I click on the parent <li>, the correct content of the child <sub> does not show up. Each category like "colors, shapes, sizes" should have corresponding child categories like "green, ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Utilizing Vuetify 2 skeleton-loader to customize loading states through Vuex store manipulation

Utilizing the Vuetify v-skeleton-loader component to wrap a v-data-table component. The server-side pagination and sorting in the data-table component are set up. To enable server-side pagination, the documentation recommends monitoring the options objec ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

AngularJS Code is displayed upon page refresh or loading

Just starting out with AngularJS. Currently working on retrieving data from a Rest API and displaying it on the page. Here is the code snippet I am using: $http.get(local_url+'/data'). then(function(response) { $scope.data = respon ...

Is there a way to incorporate the ACE code editor into a Vue project without relying on its built-in Vue

Just starting out with Vue and I'm looking to incorporate the ace code editor (this package) into my project. However, I want to avoid using the vue2-component & vue3-component versions for learning purposes. How can I achieve this? What's t ...