I am trying to make a simple shopping website using mainly PHP
and HTML
. Inside PHP
, I created objects from a class
, and those objects are in array
. Now inside HTML
, I am printing each object's photo and name
using PHP's
foreach
. Since this is a shopping website, I have added a FORM
under each item photo where the customer can type in the number of the items they wish to purchase. The default value is 0. Now, using angularJS
, What I want to do is: 1)when the value(the number of the items they want) is 0, nothing happens and the webpage prints nothing. 2)when the value is more than 0, print the number * the price right next to the form
, so the user can see in real time how much the total is going to be for that specific item.
Here is my code..
<?php
class Stock{
public $name; //in real program it is private.
public $price;
}
//Create objects and initialize them by giving each of them name and price
//Assume there are 3 objects
$items = array($object1, $object2, $object3);
?>
//now in HTML code
<form method="POST" action="order.php">
<?php foreach($items as $item): ?>
<!--Print name and price of each -->
<input type="text" value="0" name="<?php echo $item->name; ?>"> {{ <!--*****--> }}
<?php endforeach ?>
I want to print the product of the number * price of the item right next to the form only if the value is greater than 0. I tried adding ng-model="quantity"
inside input tag and wrote {{ quantity * $_POST[$item->name] }}
. However, this does not fully work. This does print the product, but because it is inside foreach
, when I change the value in the form
for an item, the values for the other items' form change along with it. How can you apply angularJS
only for the specific item?
Your loop must be in angular to do this.
So you could bind it as a model ..
FORM.PHP
<div ng-app="appModule">
<form action="order.php" method="post" ng-controller="orderFormController">
<div ng-repeat="item in itemList">
{{ item.name }} (price - {{ item.price }}): <input type="text" value="0" name="{{item.name}}" ng-model="qty[item.name]" />
Total: <span ng-if="qty[item.name] > 0">{{ item.price*qty[item.name] }}</span>
</div>
</form>
</div>
MODULE.JS
var app = angular.module("appModule", []);
app.controller("orderFormController", function($scope) {
// $scope.itemList - ajax your item list here
$scope.itemList = [
{name: 'Pencil', 'price': 10},
{name: 'Paper', 'price': 2},
{name: 'Folder', 'price': 13},
];
});
Change the value inside the input tag. Refer to HTML input value Attribute on W3 Schools.
<input value='<?php // your php code ?>' />