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?
CodePudding user response:
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/app/hello.component.ts
CodePudding user response:
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?