kevinlinxp
12/31/2016 - 5:31 AM

AngularJS:$watch

AngularJS:$watch

var updatingByJSON = false;
var updatingByComponent = false;

// Will be triggered by user editing
$scope.$watch(angular.bind(this, function () {
  return this.formJson; // `this` IS the `this` above!!
}), function (val, old) {
  if (updatingByComponent) {
    return;
  }

  updatingByJSON = true;
  if (val && val !== old) {
    try {
      vm.form.items = vm.formObjects = JSON.parse(vm.formJson);
      vm.itParsesForm = true;
    } catch (e) {
      vm.itParsesForm = false;
    }
  }

  $timeout(function () {
    updatingByJSON = false;
  });
});

// Will be triggered by DnD
$scope.$watch(angular.bind(this, function () {
  return this.formObjects; // `this` IS the `this` above!!
}), function (val) {
  if (updatingByJSON) {
    return;
  }

  updatingByComponent = true;
  vm.formJson = JSON.stringify(val, undefined, 2);

  $timeout(function () {
    updatingByComponent = false;
  });

}, true);