AngularJS - Order Form: A Beginner's Guide

Hello there, future AngularJS wizards! Today, we're going to embark on an exciting journey into the world of AngularJS order forms. Don't worry if you've never written a line of code before – we'll start from the very basics and work our way up. By the end of this tutorial, you'll be creating dynamic order forms like a pro!

AngularJS - Order Form

What is AngularJS?

Before we dive into order forms, let's take a moment to understand what AngularJS is. Imagine you're building a house. HTML is like the bricks and mortar, CSS is the paint and decorations, and AngularJS? Well, that's like the smart home system that makes everything interactive and dynamic.

AngularJS is a JavaScript framework that extends HTML with new attributes, making it perfect for creating dynamic web applications. It's like giving superpowers to your otherwise static HTML!

Setting Up Our Project

First things first, let's set up our project. We'll need to include the AngularJS library in our HTML file. Here's how we do it:

<!DOCTYPE html>
<html ng-app="orderApp">
<head>
    <title>My AngularJS Order Form</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
    <!-- Our form will go here -->
    <script src="app.js"></script>
</body>
</html>

In this code, we're doing a few important things:

  1. We've added ng-app="orderApp" to the <html> tag. This tells AngularJS that this is the root element of our application.
  2. We've included the AngularJS library using a <script> tag.
  3. We've also included our own JavaScript file (app.js) where we'll write our AngularJS code.

Creating Our AngularJS Module and Controller

Now, let's create our app.js file and set up our AngularJS module and controller:

var app = angular.module('orderApp', []);

app.controller('OrderController', function($scope) {
    $scope.order = {
        items: [],
        total: 0
    };
});

Here's what's happening:

  1. We're creating an AngularJS module named 'orderApp'.
  2. We're defining a controller named 'OrderController'.
  3. Inside the controller, we're initializing an order object on the $scope. This object will hold our order items and total.

Building the Order Form

Now, let's create our order form in the HTML:

<div ng-controller="OrderController">
    <h2>Place Your Order</h2>
    <form>
        <label>Item Name: <input type="text" ng-model="newItem.name"></label><br>
        <label>Price: $<input type="number" ng-model="newItem.price"></label><br>
        <button ng-click="addItem()">Add Item</button>
    </form>

    <h3>Order Summary</h3>
    <ul>
        <li ng-repeat="item in order.items">
            {{item.name}} - ${{item.price}}
            <button ng-click="removeItem($index)">Remove</button>
        </li>
    </ul>
    <p>Total: ${{order.total}}</p>
</div>

Let's break this down:

  1. We're using ng-controller to associate this section with our OrderController.
  2. We have input fields for item name and price, using ng-model to bind them to newItem.name and newItem.price.
  3. We have an "Add Item" button that calls an addItem() function when clicked.
  4. We're using ng-repeat to display each item in the order.
  5. Each item has a "Remove" button that calls a removeItem() function.
  6. We're displaying the total order amount.

Implementing the Controller Logic

Now, let's add the necessary functions to our controller:

app.controller('OrderController', function($scope) {
    $scope.order = {
        items: [],
        total: 0
    };

    $scope.newItem = {name: '', price: ''};

    $scope.addItem = function() {
        $scope.order.items.push({
            name: $scope.newItem.name,
            price: parseFloat($scope.newItem.price)
        });
        $scope.calculateTotal();
        $scope.newItem = {name: '', price: ''};
    };

    $scope.removeItem = function(index) {
        $scope.order.items.splice(index, 1);
        $scope.calculateTotal();
    };

    $scope.calculateTotal = function() {
        $scope.order.total = $scope.order.items.reduce(function(sum, item) {
            return sum + item.price;
        }, 0);
    };
});

Here's what each function does:

  1. addItem(): Adds a new item to the order, calculates the new total, and resets the input fields.
  2. removeItem(): Removes an item from the order and recalculates the total.
  3. calculateTotal(): Sums up the prices of all items in the order.

Enhancing User Experience

To make our form more user-friendly, let's add some validation:

<form name="orderForm" ng-submit="addItem()" novalidate>
    <label>Item Name: <input type="text" ng-model="newItem.name" required></label><br>
    <label>Price: $<input type="number" ng-model="newItem.price" min="0" step="0.01" required></label><br>
    <button type="submit" ng-disabled="orderForm.$invalid">Add Item</button>
</form>

And update our controller:

$scope.addItem = function() {
    if ($scope.orderForm.$valid) {
        $scope.order.items.push({
            name: $scope.newItem.name,
            price: parseFloat($scope.newItem.price)
        });
        $scope.calculateTotal();
        $scope.newItem = {name: '', price: ''};
        $scope.orderForm.$setPristine();
    }
};

These changes:

  1. Add form validation to ensure all fields are filled and the price is a positive number.
  2. Disable the "Add Item" button when the form is invalid.
  3. Only add the item if the form is valid.
  4. Reset the form to its pristine state after adding an item.

Conclusion

Congratulations! You've just built a functional AngularJS order form. We've covered the basics of AngularJS, including modules, controllers, two-way data binding, and form validation. Remember, practice makes perfect, so don't be afraid to experiment and expand on this form. Maybe add a discount feature or the ability to save orders? The possibilities are endless!

Here's a table summarizing the main AngularJS directives we've used:

Directive Purpose
ng-app Defines the root element of an AngularJS application
ng-controller Specifies a controller for a section of the application
ng-model Creates two-way data binding
ng-click Specifies a function to run when an element is clicked
ng-repeat Repeats an element for each item in a collection
ng-submit Specifies a function to run when a form is submitted
ng-disabled Disables an element based on a condition

Happy coding, and remember – every expert was once a beginner. Keep practicing, and you'll be an AngularJS master in no time!

Credits: Image by storyset