1

Let's say I pass a variable myvar from my router to the view-

app.get('/test', function(req, res) {
    res.render('testPage', {
        myVar: true
    });
}

Now I can use this variable in the view within script tag like this -

<script>
  var myVar = <%- JSON.stringify(myVar) %>;
  console.log(myVar); // prints 'true'
</script>

What I want to do is reset the view variable myVar to false however that isn't happening.

<script>
  var myVarJS = <%- JSON.stringify(myVar) %>;
  console.log(myVarJS); // prints 'true'
  <%- myVar = false %>;
  myVarJS = <%- JSON.stringify(myVar) %>;
  console.log(myVarJS); // still prints 'true'
</script>

The scenario is that one can pass view variables from the router with a value. Now I would like to change the value of that variable from my client side javascript.

The templating engine for views that I am using is EJS.

Kindle Q
  • 944
  • 2
  • 19
  • 28
rnjai
  • 1,065
  • 2
  • 17
  • 32
  • whats the scenario? Can't you create new variable based on myVar? can you please tell us the use case? – Deendayal Garg Mar 31 '16 at 05:35
  • @DeendayalGarg i have edited the last code snippet in my question. – rnjai Mar 31 '16 at 05:37
  • @DeendayalGarg the scenario is that you can pass view variables from the router with a value.Now i would like to change the value of that variable from my client side javascript.Any more questions? – rnjai Mar 31 '16 at 05:38
  • @rnjai you are not trying to change the value from your client side javascript, you are trying to change the value while parsing your template. The question still remains. Why? – trex005 Mar 31 '16 at 05:41
  • @trex005 it is a bit too complex too explain.What i want to do is - " the scenario is that you can pass view variables from the router with a value.Now i would like to change the value of that variable from my client side javascript." – rnjai Mar 31 '16 at 05:46
  • I would suggest you to check this out if you haven't. http://stackoverflow.com/questions/16098397/pass-variables-to-javascript-in-expressjs – Deendayal Garg Mar 31 '16 at 05:51
  • @DeendayalGarg The question you have shown help me use the variable in the view within within script tag but not set it. – rnjai Mar 31 '16 at 05:55
  • See if this helps you out : http://stackoverflow.com/questions/28603658/can-a-js-script-get-a-variable-written-in-a-ejs-context-page-within-the-same-fil – trex005 Mar 31 '16 at 05:59
  • Try changing `<%- myVar = false %>;` to `<% myVar = false %>;` – trex005 Mar 31 '16 at 06:06
  • It worked !! Thanks , please convert it to an answer. @trex005 – rnjai Mar 31 '16 at 06:10

1 Answers1

1

Change <%- myVar = false %>; to <% myVar = false %>;

trex005
  • 5,015
  • 4
  • 28
  • 41