1

I am trying to initialize a constant with global variable in my angularJS like this:

var app = angular.module('myApp')
.constant('test1', myTest.test1)
.constant('test2', myTest.test2);

The problem is sometimes global variable myTest is not available due to which it throws an error that myTest is not defined. I have tried this also:

.constant('test1', angular.isDefined(myTest)?myTest.test1:'')
.constant('test2', angular.isDefined(myTest)?myTest.test2:'')

But it still throws the same error. Is there any workout to this?

1
  • is myTest available in window? Commented Apr 2, 2015 at 4:42

2 Answers 2

2

angular.isDefined will not work if there is referenceError.

You may need to use:

.constant('test1', typeof myTest != "undefined"? myTest.test1 : "");

It's because of ReferenceError.

Better You include your angular code below the file which is setting the myTest property.

if script.js is setting your myTest object, then

window.myTest = {
   test1 : "Some value"
}

Then insert your angular app script below it,

var app = angular.module('myApp')
.constant('test1', myTest.test1)
.constant('test2', myTest.test2);

In this case, it will be always defined.

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

2 Comments

You know what i was typing the same typeof operator :-P Now +1 for you Bingo :-)
@codelearner angular.isDefined is also throw error in case variable is not defined .Only javascript typeof operator manage this king of erro :)
0

you can put your global constant in your html file inside of script tag before anything else loads like this

script
var test1= test1|| 'some value';
script

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.