简体   繁体   English

如何在angularjs应用程序中包含全局变量?

[英]How to include global variables in angularjs app?

I have a global variable declared outside of angular context: 我在角度上下文之外声明了一个全局变量:

var globalv = "Hello"; var globalv =“ Hello”;

This variable does not change. 该变量不变。 I have a directive that wants to use it... 我有一个想要使用它的指令...

$scope.somevar = globalv + "_";

What is the simplest way to include the globalv in my angularjs app/context? 在我的angularjs应用程序/上下文中包含globalv的最简单方法是什么? When I attempt to reference it in the above manner, I get an error. 当我尝试以上述方式引用它时,出现错误。

I would consider wrapping the value in an angular constant which will enable you to inject it only where its needed 我会考虑将值包装在一个角度常量中,这将使您能够仅在需要时将其注入

var myApp = angular.module('myApplication',[]);
myApp.constant('myConstant', globalv);

Just ensure that the globalv variable is defined before your angular module is defined. 只需确保在定义角度模块之前就定义了globalv变量即可。

I like this better than using a rootscope/global variable since you can control who the consumers of the value are. 我比使用rootscope / global变量更好,因为您可以控制值的使用者。

You can inject the constant like so: 您可以像这样注入常量:

mayApp.directive('myDirective',['myConstant',
        function (myConstant) {
            return {
                ..
        };
}]);

Is there any reason why you couldn't include it in the angular context? 有什么理由不能将其包含在角度环境中? If it absolutely needs to be global you can add it to the rootscope within the angular context. 如果绝对需要全局,则可以在角度上下文中将其添加到rootscope。

/* declare rootscope variables when the angular app starts*/
angular.module('someApp').run(function ($rootScope) {
    $rootscope.globalv = "Hello";
});

You can then reference that rootscope variable anywhere within your angular app. 然后,您可以在您的角度应用程序中的任何位置引用该rootscope变量。

This is pretty simple to me, but I personally hate using $rootScope unless I have to. 这对我来说很简单,但是除非需要,否则我个人讨厌使用$ rootScope。 You should really try and get away from global variables. 您应该真正尝试摆脱全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM