Lars Mertens
Lars Mertens

Reputation: 1439

How to correctly send php variables through ng-click parameters

Currently i'm trying to send a time and a date from php to my angular controller by using a ng-click.

$time is a date
$today is a datetime

Can someone explain me why this works

<button ng-click="getClickInfo('<?php echo $time; ?>', '<?php echo $today; ?>')";</button>

But when i try to achieve the same result within an echo like this, it gives me different and incorrect output

<?php echo '<button ng-click="getClickInfo(' . $time . ', ' . $today . ')";></button>'; ?>

I tried to search on the internet for a solution but i couldn't really find a topic about it. Hope someone can explain me what is happening in this scenario. Redirection to any articles on this topic would be really helpfull for me.

Output:

01:00 // incorrect output
01/01/1970 // incorrect output

20.30 // desired output
22-04-2016 // desired output

Upvotes: 0

Views: 709

Answers (1)

Tudor Ilisoi
Tudor Ilisoi

Reputation: 2944

You have to quote the javascript function arguments, otherwise you get unpredictable results The ctach here is that the HTML ng-click attribute must be enclosed in double quotes and the attribute value (your function) must not contain double quotes, because it would break the HTML

Furthermore, the ; is not needed, you're putting it outside the ng-click HTML attribute value, that is not valid HTML

Here's a fix, note that quotes are escaped with backslash inside PHP strings:

<?php echo '<button ng-click="getClickInfo(\'' . $time . '\', \'' . $today . '\')"></button>' ?>

Here's a more readable way to do it, I would recommend this approach:

<?php echo '<button ng-click="getClickInfo(' . "'$time', '$today'" . ')";></button>' ?>

Upvotes: 1

Related Questions