Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Read and edit global javascript variable from Angular

I have an angular app where in my index.html i have a variable inside a tag, like this:

<script type="text/javascript">
let global = 5;
</script>

I need to read and edit the value of this variable, inside an angular component, but I do not know how to do it.

I saw that it is possible to read the value if you create the variable inside the "window" object of javascript (window.global = 5) and then use it in angular component, but i think it would not work for me because i need that variable to be outside, as specified above.

Is it possible? Any ideas?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The keyword declare to the rescue: first, declare your global with var (let doesn't work)

<script type="text/javascript">
  var someVar = 5;
</script>

and access it in, say, Angular component:

declare var someVar;
// ...
    this.foo = someVar;

https://stackblitz.com/edit/angular-ivy-zjpnzq?file=src%2Fapp%2Fhello.component.ts

about 4 years ago · Juan Pablo Isaza Report

0

Finally I used an aproximation of @robin-zigmond answer. I changed let to var in the script tag and in my angular component I access the variable using:

window["global"]

I can edit the value inside a component using, for example:

window["global"] = 6

enter image description here

Moreover, I tried @mbojko answer and it worked too.

about 4 years ago · Juan Pablo Isaza Report

0

You can pass the window varaible to the scope in your controller.

<!DOCTYPE html>
<html>
<script>window.HELLO_MSG = 'Hello,';</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
{{ wlcmMsg + " " + firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.wlcmMsg = window.HELLO_MSG;
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>

</body>
</html>

Or you can inject the whole window object like here: How to inject window into a service?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!