AngularJS: $watch event was not fired

Attempting a simple task here.

Inside my controller:

  $scope.testObject = { name : 'john' };

  $scope.$watch('$scope.testObject.name', function (e, n, v) {
      console.log('reached');
  });

In my view:

  <input type="text"  ng-model="testObject.name"/>

The input field is connected to the testObject's name property and upon loading the controller, it enters the $watch function.

But when I modify the input value, the $watch function doesn't get activated. Any idea why?

I also attempted setting the third parameter of $watch to true, but it had no impact.

Answer №1

To enhance your code, consider eliminating the $scope from your watch function. Here is a revised example:

$watch('testObject.name', function(event, newValue, oldValue){
    console.log("The event was triggered");
});

Answer №2

Try using the following code snippet:

$scope.$watch('testObject.name', function(e,n,v){
    console.log("reached");
});

If you want to add another observer, you can do it like this:

$scope.$watch('testObject.attr1 + testObject.attr2', function(e,n,v){
    console.log("reached");
});

Alternatively, you can use the following syntax:

$scope.$watch('testObject', function(e,n,v){
    console.log("reached");
}, true);

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

"Encountering an issue where the route function in Passport and ExpressJS is not being

When using passport for admin authentication, I am facing an issue where the redirect is not calling my function. Consequently, all that gets printed on login is [object Object] Here is my code: app.get('/admin', isLoggedIn, Routes.admin); ...

Do overlay elements have to be positioned at the bottom of the HTML body every time?

As I delve into the world of JavaScript frameworks, one common trend I've noticed is that elements like dialogs, tooltips, and alerts usually appear at the end of the body tag. With my own implementation of these UI elements, I am determined to make ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...

What is the best way to execute a function individually for every tag within a vue.js application?

I'm currently exploring the world of Vue JS and I thought it would be interesting to experiment with something new. Sometimes looking at the code first makes understanding it much easier than a lengthy explanation. Check out this code snippet on jsFi ...

Typescript is requesting an index signature for a nested object that has been validated by Zod and is being received from an API request

This project uses Typescript 4.4.4, Next.js 11.1.2, and Zod 3.9.3. Typescript is throwing an error that says: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type <Review Type> ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

Optical Character Recognition (OCR) tool

Does anyone have recommendations for a JavaScript OCR API that can easily be accessed via JavaScript? I'm searching for an API similar to this: upload an image along with the desired result type (e.g. numbers, objects, text, mixed, etc) and receive t ...

Node.js encountered an error: Address already in use. The specified port 8080 is currently being utilized by another application

My application was not functioning properly, and upon running the command "npm start", an error was thrown: Error: listen EADDRINUSE: address already in use :8080 Even after restarting my EC2 instance and attempting the command again, I encount ...

Troubleshooting the issue: Incompatibility between jQuery .focus() and dynamically generated list items from ng-repeat in AngularJS

I am currently working on enhancing the keyboard accessibility of a website, specifically focusing on making a dropdown menu accessible via keyboard. I am attempting to establish focus on the element with the id= list-0. Below is the HTML code snippet: & ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

Ways to conceal an animated gif once it has been downloaded?

Is it possible to have an animated gif image vanish once server-side Java code runs and the client receives an HTTP Response from the webserver without relying on Ajax? I am currently utilizing the following Struts2 submit button: <s:submit value="sho ...

What is the method for configuring the URL of an ajax request to open in a separate window?

I am currently working on an ajax call where I need to open a URL in a new tab or window. Since I'm still learning about ajax, I would greatly appreciate any help and explanation that you can provide. Below is the code snippet: $.ajax({ url: &apo ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

Creating a layered structure in React using custom components within the Material-UI tree

As someone new to the world of React and Javascript, I am struggling to understand why my code is not behaving as expected. I am attempting to create a tree structure using custom components as branches. However, when I run the code, the child objects do n ...

Can anyone recommend any quality libraries for uploading files in Silverlight or HTML that also support metadata?

I am in the process of developing a solution within SharePoint 2010 that allows for the upload of multiple documents while also tagging them with metadata. Is there anyone familiar with an innovative file-upload control or solution that enables the additi ...

Sending Text Input Data from Angular Form to a Restful API

I'm currently working on a project where I need to send data from a reactive form to a REST API running on my local express.js server. The form consists of basic text input fields like name, surname, and email. When the form data is submitted, it is ...

Upon loading, the Carousel is visible instead of being hidden, which is contrary to its intended behavior

Any help would be greatly appreciated as I am struggling with creating a web page featuring tabs for "London, New York, Shanghai". The initial page displayed is the "welcome" page with the other tabs hidden on load. I successfully implemented a carousel f ...

What is the best way to manage asynchronous functions when using Axios in Vue.js?

When I refactor code, I like to split it into three separate files for better organization. In Users.vue, I have a method called getUsers that looks like this: getUsers() { this.isLoading = true this.$store .dispatch('auth/getVal ...

Guide to accessing a particular object key within an array by leveraging the MUI multiple autocomplete feature coupled with the useState hook

How can I retrieve the id key from a selected object in a given array list and set it to the state? You can find a sandbox example at this link: https://codesandbox.io/s/tags-material-demo-forked-ffuvg4?file=/demo.js ...

Tips on automatically focusing on an input within a Semantic UI React dropdown

I'm attempting to automatically focus on an input located within a Semantic UI React dropdown by using a ref, but unfortunately, it's not functioning as expected. The input should be focused when the dropdown is opened. Check out the code sandbox ...