2016-11-14 71 views
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" 
    } 
}); 
+0

你为什么不尝试使用NG-变化,而不是$看? – holtc

+0

谢谢!我知道解决方案是简单的... ng-change就像一个魅力...请设置您的评论作为答案,所以我可以授予您 – johan

+0

您的指令中的隔离范围也可以是一个解决方案..看到[这里] (https://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope) –

回答

0

尝试使用NG-变化,而不是$手表,它的清洁和更容易跟随。

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