This may or may not be a good approach but I was able to share variables between link
and controller
the following way:
angular.module("myApp")
.directive("loadtime", [
function(){
let startTime;
function setStartTime(){
if(!startTime){
startTime = new Date().getTime();
}
}
let endTime;
function setEndTime(){
if(!endTime){
endTime = new Date().getTime();
}
}
return {
restrict: 'AE',
link: function (scope, element, attrs) {
scope.$watch('dataLoaded', function(newValue, oldValue){
if(newValue === true) {
setEndTime();
console.log(`data finished loading for ${attrs.id} at ${endTime}!`);
console.log(`total time to load (in ms): ${(endTime - startTime)}`);
}
});
},
controller: function($scope, $element, $attrs) {
setStartTime();
console.log(`Loading has started on ${startTime}`);
}
};
}
]);
Essentially just declare variables in the outermost function of the directive and set their values using a function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…