Angular指令实例$ watch无法正常工作

时间:2016-11-14 21:08:56

标签: javascript angularjs jquery-ui-timepicker

我有两个时间戳输入,我需要计算总数。 我的指令中的代码工作正常但问题来自我在页面上有多个指令。 我尝试在我的指令控制器或链接函数中设置监视,但监视只处理最后一个实例化指令。

我可能错过了什么?

编辑:抱歉错误的plunkr

这是一个傻瓜:https://plnkr.co/edit/uC38NIbYsy9Vv3S38xHh?p=preview

指令代码:

 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 个答案:

答案 0 :(得分:0)

尝试使用ng-change而不是$ watch,它更干净,更容易理解。

答案 1 :(得分:0)

它与你的_calc函数声明没有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();
},

Plnkr上的工作样本