Angular directive instances $watch not working

93 views Asked by At

I have two timepicker inputs that has a total that I need to calculate. The code in my directive works fine but the problem comes when I have more than one of the directives on the page. I tried setting the watches in my directive's controller or in the link function but the watches are only working on the last instantiated directive.

What am I possibly missing?

Edit: Sorry wrong plunkr

Here's a plunkr: https://plnkr.co/edit/uC38NIbYsy9Vv3S38xHh?p=preview

Directive code:

 myApp.directive('myTimepicker', function() {
  return {
    restrict: 'A',
    scope: {
      tmodel: '=',
      ttitle: '@'
    },
    link: function(scope, $element, attr) {
      console.log(scope);
      scope.tform = scope.tmodel;
      scope.$watch('tform.on', function(newValue, oldValue) {
        // console.log("calc on"+scope.ttitle);
        _calctotal();
      });
      scope.$watch('tform.off', function(newValue, oldValue) {
        // console.log("calc off");
        _calctotal();
      });
      _calctotal = function() {

        var on = new Date(scope.tform.on);
        var off = new Date(scope.tform.off);
        var total = off.getHours() - on.getHours();
        var totalmin = off.getMinutes() - on.getMinutes();
        if (totalmin < 0) {
          total = total - 1;
          totalmin = totalmin * -1;
        }
        if (total < 0) {
          total = "Invalid";
          totalmin = "";
        }
        if (totalmin < 10) totalmin = "0" + totalmin;
        scope.tform.total = total + ":" + totalmin;

      };
      _calctotal();
    },
    controller: function($scope) {
      // console.log($scope);

    },
    templateUrl: "mytimepicker.html"
  }
});
2

There are 2 answers

0
holtc On BEST ANSWER

Try using ng-change instead of $watch, it's cleaner and easier to follow.

0
Sreekanth On

Its with your _calc function declaration without a var.

link: function(scope, $element, attr) {
  console.log(scope);
  scope.tform = scope.tmodel;
  var _calctotal = function() {

    var on = new Date(scope.tform.on);
    var off = new Date(scope.tform.off);
    var total = off.getHours() - on.getHours();
    var totalmin = off.getMinutes() - on.getMinutes();
    if (totalmin < 0) {
      total = total - 1;
      totalmin = totalmin * -1;
    }
    if (total < 0) {
      total = "Invalid";
      totalmin = "";
    }
    if (totalmin < 10) totalmin = "0" + totalmin;
    scope.tform.total = total + ":" + totalmin;

  };
  scope.$watch('tform.on', function(newValue, oldValue) {
    // console.log("calc on"+scope.ttitle);
    _calctotal();
  });
  scope.$watch('tform.off', function(newValue, oldValue) {
    // console.log("calc off");
    _calctotal();
  });

  _calctotal();
},

Working sample on Plnkr