简体   繁体   中英

How to custom $watch in angular js?

I want to have a custom $watch . This watch I will make on a variable. I want when a the value of a variable is changed to see a message, and when the variable is not change his value to see another message.

An example is the next one: I have a textbox where I watch when a user writes something. I want to see a message when he writes something and when stop to see another message.

You can check with a timeout:

$scope.$watch("myVar",
              function handleMyVarChange( newValue, oldValue ) {
                 //Change Display Message to Editing Message

                 //Timeout to checkif stop writing
                 $timeout(function (newValue) {
                 if(newValue === myVar) {
                   //Change Display Message to Not Editing Message
                }
               }, 100);
             }
);

The concept I would recommend is called debounce in many javascript libraries. You give a function to call and a length of time that must pass without the function being called again before a callback is fired. Often times you can supply the option of firing the callback on the initial call as well. This would allow you to flip a switch on the first call, then flip it back once the amount of time has passed without the function being called again.

See: http://davidwalsh.name/javascript-debounce-function

Ex:

(a better example would create a debounce service using $timeout eliminating the need for $scope.$evalAsync() )

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  var toggle = debounce(function() {
    $scope.typing = !$scope.typing;
    $scope.$evalAsync();
  }, 500, true)

  $scope.$watch('name', toggle)
});

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this;
    var args    = arguments;
    var callNow = immediate && !timeout;

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);

    if (callNow){
      func.apply(context, args);
    }

    function later() {
      timeout = null;
      func.apply(context, args);
    }
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM