Angularjs如何从app.directive()访问app.run()中的变量?

时间:2019-01-16 08:44:47

标签: angularjs

如何从app.directive()访问angularjs 1.7中的app.run()变量

angular.module('myApp', [

]).config(function(){

  // someCodes

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

我想在这里在指令()中访问“ var getLifeSpan”

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

这可能吗?

2 个答案:

答案 0 :(得分:2)

在.run()函数中需要$ rootScope,将变量放入$ rootScope,并在访问$ rootScope.yourVar的指令中输入

例如

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

在您的指令中,使用$rootScope.getLifeSpan(whatever)

答案 1 :(得分:1)

据我所知,不可能以这种方式访问​​您的功能。 但是您可以创建服务,并从控制器/指令/组件等访问功能。

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

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

然后,您可以使用依赖注入从指令中访问此服务

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