2

I'm having an issue with AngularJS in that there are problems when I reuse variable names across two templates. A simplified version of my setup is as follows, two pages declared in route.js

$routeProvider.when('/a', {
  templateUrl: 'a.html'
})
.when('/b', {
  templateUrl: 'b.html'
})

each page (a.html and b.html) has a script tag like so

<script type="text/javascript">
  let foo = 5;
</script>

there is also a navigation menu for navigating between the pages. The issue is that when I go from one page to the other, I get an errror

Uncaught SyntaxError: Identifier 'foo' has already been declared

I know I can just change the variable name, but I want to know why this is happening because my instinct is that it shouldn't be. Am I wrong to be using script tags with Angular? Is this potentially caused by something else? Thanks

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Burgan
  • 880
  • 1
  • 7
  • 24
  • 2
    `var` statements allow re-declaration; ES6 `let` statements forbid re-declaration. Since you are doing it on global scope, there is no need to use a `let` statement. – georgeawg Jun 08 '18 at 15:33
  • Possible duplicate of [What's the difference between using “let” and “var” to declare a variable in JavaScript?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav) – georgeawg Jun 08 '18 at 15:37

1 Answers1

2

Here:

<script type="text/javascript">
  let foo = 5;
</script>

You're declaring the variable in the global scope, and when you trigger the second route you're redeclaring the same variable that is already in the same scope.

Avoid using the script tag and use the controllers local scope, declare the variables there and you won't have any conflict.

function aController (){
  let foo = 5;
}

function bController (){
  let foo = 5;
}

Alternatively if you want to keep the script block wrap the code in an IIFE to avoid messing with the global scope.

<script type="text/javascript">
  (function(){
     let foo = 5;
  })()
</script>
Karim
  • 8,454
  • 3
  • 25
  • 33
  • so i need to add controllers to both pages in `route.js` ? – Burgan Jun 08 '18 at 14:58
  • well i don't know your business logic, the thing is you should avoid changing the global scope to avoid these types of errors. you can even use an IIFE in the script block in order to use the scope of the function rather then the global – Karim Jun 08 '18 at 15:02