如何在 JS 指令的不同部分之间共享变量?

How to share a variable between different parts of a JS directive?

我正在尝试在指令的 linkcontroller 部分之间共享数据,总体目标是衡量 div 执行所需的时间更改要加载的页面的状态/数据。

angular.module("myApp")
.directive("loadtime", [
  function(){
      return {
          restrict: 'A',
          link: function (scope, element, attrs) {
              scope.$watch('dataLoaded', function(newValue, oldValue){
                  if(newValue === true) {
                      var endTime = new Date().getTime();
                      console.log(`data finished loading for ${attrs.id} on ${endTime}!`);
                      console.log(`total time to load (in ms): ${(element.startTime - endTime) / 1000}`);
                  }
              });
          },
          controller: function($scope, $element, $attrs, $injector) {
              var startTime = new Date().getTime();
              console.log(`Loading has started on ${startTime}`);
          }
      };
  }
]);

在指令中设置变量然后在指令的不同 sections/parts 中访问它们的最佳方法是什么?

这可能是也可能不是一个好方法,但我能够通过以下方式在 linkcontroller 之间共享变量:

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}`);
        }
    };
}
]);

基本上只是在指令的最外层函数中声明变量并使用函数设置它们的值。