Using $watch to monitor model changes in Angular.js

Source: Internet
Author: User

$watch Simple to use

$watch is a scope function that listens for model changes and notifies you when the part of your model changes.

$watch (watchexpression, Listener, objectequality);

The description of each parameter is as follows:

    1. Watchexpression: The Listener object, which can be a angular expression such as ' name ', or function such as functions () {return $scope. Name}.

    2. Listener: The function or expression that will be called when watchexpression changes, it receives 3 parameters: NewValue (new value), OldValue (old value), scope (scope reference)

    3. Objectequality: If the depth listener is set to true, it tells angular to check for changes in each property in the monitored object. If you want to monitor an individual element of an array or an object's properties instead of a normal value, you should use it

Example:

1$scope. Name = ' Hello ';2 3 varWatch = $scope. $watch (' name ',function(Newvalue,oldvalue, scope) {4 5 Console.log (newvalue);6 7 Console.log (oldValue);8 9 });Ten  One$timeout (function(){ A  -$scope. Name = "World"; -  the},1000);

$watch Performance Issues

Too many $watch will cause performance problems, $watch if they are no longer used, we'd better let them out.

The $watch function returns a function that unregisters the listener, and if we want to monitor a property and then unregister it later, you can use the following method:

1 var watch = $scope. $watch (' Somemodel.someproperty ', callback); 2 3 // ... 4 5 Watch ();

There are also 2 functions related to $watch:

1 $watchGroup (watchexpressions, listener); 2 3 $watchCollection (obj, listener);

Using $watch to monitor model changes in Angular.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.