我有兩個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"
}
});
你爲什麼不嘗試使用NG-變化,而不是$看? – holtc
謝謝!我知道解決方案是簡單的... ng-change就像一個魅力...請設置您的評論作爲答案,所以我可以授予您 – johan
您的指令中的隔離範圍也可以是一個解決方案..看到[這裏] (https://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope) –