Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda