Using AngularJS data binding, I'd like to return num1 * num2 as user type num2; num1 is a PHP variable (cannot be changed by user). Following, How do I pass PHP variables to angular js?, I tried:
<!doctype html>
<html>
<head>
<title>AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body>
<? php $num1 = 5;?>
<div ng-app="myApp" ng-controller="myCtrl">
<form action="/action_page.php">
<div id="num1">
Num1: <div ng-model="num1" ng-init="num1('<?php echo $num1?>')">
</div>
Num2: <div id="num2" ng-model="num2">
<input type="number">
</div>
Multiplied: {{num1 * num2}}
<input type="submit" value="Submit">
</div>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.num1 ;
$scope.num2 ;
});
</script>
</body>
</html>
How do I pass PHP variable num1 to AngularJS app, assuming preset PHP variable num1=5?
asked Jun 4, 2018 at 18:06
Moazzem Hossen
2,5862 gold badges25 silver badges33 bronze badges
1 Answer 1
Change ng-init="num1('<?php echo $num1?>')">, to ng-init="num1 = '<?php echo $num1; ?>' ">
answered Jun 4, 2018 at 18:15
Velimir Tchatchevsky
2,8401 gold badge18 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Moazzem Hossen
I'm not sure why I can't pass PHP variable to to JS or AngularJS. Can you point out why this doesn't work?
<!doctype html> <html> <?php $num = 10; ?> <script type="text/javascript"> var num = '<?php echo $num; ?>'; console.log(num); </script> </html>. JS variable num returns <?php echo $num; ?> instead of $num's value 10.Velimir Tchatchevsky
Look at the answer. 1St you should use
echo in php to output the code, what you do is actually assigning the variable in php. 2nd you need to output the code inside the script tags, or use the {{}} operators, otherwise you are just printing text in htmlMoazzem Hossen
Can you rewrite the code in my first comment so that
console.log(num) returns num's value 10, instead of '<?php echo $num; ?>'?lang-js
echobefore that btw) your php in the html of the page. Add the{{}}so it becomes `echo "{{num1 = ".$phpNum1.";}}"