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

I’m trying to share data between the link and controller part of a directive with the overall goal being to measure the amount of time it takes for a div to change state / the data of the page to load.

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

What’s the best way to set variables within the directive to then have them accessible throughout the different sections/parts of the directive?

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *