0

我有两个 timepicker 输入,它们的总和需要计算。我的指令中的代码工作正常,但是当我在页面上有多个指令时问题就来了。我尝试在指令的控制器或链接函数中设置手表,但手表只适用于最后一个实例化的指令。

我可能错过了什么?

编辑:抱歉错了plunkr

这是一个 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"
  }
});
4

2 回答 2

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上的工作示例

于 2016-11-14T21:35:28.260 回答
0

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

于 2016-11-14T21:32:55.350 回答