0

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?

Moazzem Hossen
  • 2,276
  • 1
  • 19
  • 30
  • You are just echoing (you forgot the `echo` before that btw) your php in the html of the page. Add the `{{}}` so it becomes `echo "{{num1 = ".$phpNum1.";}}" – Velimir Tchatchevsky Jun 04 '18 at 18:12

1 Answers1

1

Change ng-init="num1('<?php echo $num1?>')">, to ng-init="num1 = '<?php echo $num1; ?>' ">

Velimir Tchatchevsky
  • 2,812
  • 1
  • 16
  • 21
  • 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? ` `. JS variable `num` returns `` instead of `$num`'s value 10. – Moazzem Hossen Jun 05 '18 at 03:18
  • 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 html – Velimir Tchatchevsky Jun 05 '18 at 03:21
  • Can you rewrite the code in my first comment so that `console.log(num)` returns `num`'s value 10, instead of `''`? – Moazzem Hossen Jun 05 '18 at 03:26