1

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?

0

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Simpler and cleanwr than mine
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.