1

I have a global variable declared outside of angular context:

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? When I attempt to reference it in the above manner, I get an error.

0

2 Answers 2

2

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.

I like this better than using a rootscope/global variable since you can control who the consumers of the value are.

You can inject the constant like so:

mayApp.directive('myDirective',['myConstant',
        function (myConstant) {
            return {
                ..
        };
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

How can this constant be used my directive? Can I just use: $scope.somevar = myConstant?
1

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.

/* 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.

This is pretty simple to me, but I personally hate using $rootScope unless I have to. You should really try and get away from global variables.

2 Comments

I have a js file included in my index.html that has all the angular.module('someApp')... I want to inject the globalv variable in my index.html page (which contains almost no javascript. In your answer, does it matter if that script tag with the code exists before or after the include of my js file that contains the start of the app (the angular.module('someApp'))?
If you're going to use angular I recommend putting all logic inside of your angular code. I'm not sure why you would need a variable in a script tag outside of your angular code.

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.