Evan
Evan

Reputation: 2507

Angularjs How can variable in app.run() be able to access from app.directive()?

How can I access the variable of app.run() in angularjs 1.7 from a app.directive()

angular.module('myApp', [

]).config(function(){

  // someCodes

}).run(function(){
   var getLifeSpan = function(LifeSpan){
   var number = eval(LifeSpan)
   return Math.abs(number);
  }
});

I want to access "var getLifeSpan" here in directive()

angular.module('myApp')
.directive('lifeSpan',  function ($rootScope) {
    return {
        link : function(scope, element, attrs){
        Some Codes. . .
     }
   }
 }

Is this possible?

Upvotes: 1

Views: 133

Answers (2)

anotherdev
anotherdev

Reputation: 2567

require $rootScope in the .run() function, put your variable in the $rootScope, and in the directives access to $rootScope.yourVar;

For example

app.run(function($rootScope) {
  $rootScope.getLifeSpan = function(LifeSpan){
    var number = eval(LifeSpan)
    return Math.abs(number);
  };
});

In your directives, use $rootScope.getLifeSpan(whatever)

Upvotes: 2

icydemon
icydemon

Reputation: 78

It is not possible, as far as I am aware, to access your function in this way. But you can create a service, and access your function from your controllers / directives / components, etc.

function lifeSpanService() {
   let service = {};
   service.getLifeSpan = (LifeSpan) => {
      var number = eval(LifeSpan)
      return Math.abs(number);
   }

   return service;
}
angular.module('myApp')
    .service('lifeSpanService', lifeSpanService);

Then you can use dependency injection to access this service from your directive

angular.module('myApp')
    .directive('lifeSpan', ['$rootScope', 'lifeSpanService', ($rootScope, lifeSpanService) => {
        return {
            link : (scope, element, attrs) => {
                let value = 1;
                let lifespan = lifeSpanService.getLifeSpan(1);
            }        
    }]);

Upvotes: 1

Related Questions