Getting Property Change With $watch in AngularJS

Quite often we want to perform some actions when a value of a property changes. In Angular we track the changes of a property by continuously watching it using $watch. Let's go through an example to understand how it works.

We have two input boxes for the user to enter numbers. We will display the sum of those numbers in the paragraph tag below. Now these input boxes are bound to two properties in the controller, number1 and number2. We will be watching these properties and when any of them changes, we again calculate the total and display them onto the screen by assigning the latest values to another property, total.

program

The $watch function takes the following parameter as input.

watch function

On running the code this would be the output in the browser.

output in the browser

I hope you've liked this article. Happy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all