AngularJS : Watching ($watch) scope variables

AngularJS : Watching ($watch) scope variables

by Daan De Smedt

HTML

<div ng-app="app" ng-controller="BasicController as vm">
  Hello, {{vm.movieTitle}}!
  <br/>
  <br/>
  <button ng-click="vm.changeTitle()">
    Change title
  </button>
</div>

JavaScript

angular
  .module('app', [])
  .controller('BasicController', BasicController)

function BasicController($scope) {
  /* declare VM */
  var vm = this;
  vm.changeTitle = changeTitle;
  /* set constant to VM */
  vm.movieTitle = 'The Matrix Watcher';
  /* functions */
  function changeTitle() {
    vm.movieTitle = 'The Matrix Watcher updated';
  };

  /* watch function */
  $scope.$watch('vm.movieTitle', function(current, original) {
    // prevent inital watch cycle by checking different in 'curernt' & 'original'
    if (current !== original) {
      console.log('vm.movieTitle has changed, prev value : ' + original + ' - new value : ' + current);
    }
  });

}