Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda