我有两个 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"
}
});