我有两个需要计算总数的时间选择器输入。我的指令中的代码工作得很好,但当我在页面上有多个指令时,问题就来了。我试着在指令的控制器或链接函数中设置手表,但手表只在最后实例化的指令上工作。
我可能错过了什么?
编辑:对不起,错误的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"
}
});
尝试使用ng-change来代替$watch,这样更清晰,更容易遵循
它与你的_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的工作示例