First of all, I checked and I didn't find any article covering my question.
How to access a pre-defined js global variable in angularJS built-in directive?
For example, I define this variable in <script>var variable1 = true; </script>
Then I write a AngularJS directive:
<div ng-if="variable1">Show some hidden stuff!</div>
This does not really work.
Then I'm informed that I should use ng-init
So I wrote code somewhere else like:
<div ng-init = "angularVariable1 = variable1"></div>
And this apparently does not work as well...this is like a vicious cycle. You need to access pre-defined js global variables, then you need to use ng-init; in order to use ng-init, you need to access global variables.
Any particular way to do this?
We always need to declare global variable file for our angular 8 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily. So, in this example, we will create GlobalConstants file for adding global variables in our application.
The reason is that, when the page loads, your global variables will read the input before anything is entered. Global variables are created when the page load and deleted when the window is closed.
Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.
I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window
makes testing more difficult.
HTML:
<section ng-app="myapp" ng-controller="MainCtrl"> Value of global variable read by AngularJS: {{variable1}} </section>
JavaScript:
// global variable outside angular var variable1 = true; var app = angular.module('myapp', []); app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) { $scope.variable1 = $window.variable1; }]);
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) { $scope.variable1 = variable1; }
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With