Being new to AngularJs (1.6), I am just starting out and may not have all the right questions yet.
I have recently begun working on a project built with AngularJS 1.6.
My current task involves running a script on specific routes. For now, let's consider the following simple script:
alert('Hello World');
After extensive research, I discovered that I need to use $state
to access $state.current.name
and then utilize an if
or switch
statement in my code to run the script.
The issue I encountered with this approach is that when I try to access $state.current.name
during app loading, it returns an empty string.
To verify that $state.current.name
eventually returns a value, I implemented the following:
setTimeout(
() => console.log($state.current.name),
3000
);
This confirmed that the required value is indeed available after a short delay.
Despite trying lifecycle component methods, the run()
method of modules, and resolvers in routes, none of these solutions worked for me.
In all attempts, $state.current.name
remained empty, except when using setTimeout
.
As a temporary fix, I resorted to:
var interval = setInterval(
() => {
if ($state.current.name !== 0) {
clearInterval(interval);
alert('Hello World');
}
},
250
);
Therefore, my main question is whether there is a better solution for accessing the route name.
Edit #1
I also tried the following code:
// ...
require('angular')
.module(config.appName, moduleCollection)
.run(
$state => console.log($state.current.name)
);
Unfortunately, I am still getting an empty string :(. Any alternatives?