AngularJS - 購物車應用程式

Hello, aspiring programmers! Today, we're going to embark on an exciting journey to create a shopping cart application using AngularJS. As your friendly neighborhood computer science teacher, I'm thrilled to guide you through this process, even if you're completely new to programming. So, grab a cup of coffee (or your favorite beverage), and let's dive in!

AngularJS - Cart Application

What is AngularJS?

Before we start building our cart application, let's take a moment to understand what AngularJS is. AngularJS is a powerful JavaScript framework that helps us create dynamic web applications. It's like a Swiss Army knife for web developers, providing tools to make our lives easier and our code more organized.

Setting Up Our Project

Step 1: Creating the HTML Structure

Let's start by creating a basic HTML structure for our shopping cart application. Don't worry if you're not familiar with HTML; I'll explain each part as we go along.

<!DOCTYPE html>
<html ng-app="cartApp">
<head>
<title>My Shopping Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="CartController">
<h1>My Shopping Cart</h1>
<!-- We'll add more content here later -->
</body>
</html>

In this HTML structure, we've done a few important things:

  1. We've included the AngularJS library using a CDN link.
  2. We've linked our own JavaScript file (app.js) which we'll create next.
  3. We've added ng-app="cartApp" to the <html> tag, which tells AngularJS that this is the root element of our application.
  4. We've added ng-controller="CartController" to the <body> tag, which we'll use to manage our cart's logic.

Step 2: Creating the AngularJS Application

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

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

app.controller('CartController', function($scope) {
$scope.items = [];
$scope.total = 0;

$scope.addItem = function(item) {
$scope.items.push(item);
$scope.calculateTotal();
};

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

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

Let's break this down:

  1. We create an AngularJS module named 'cartApp'.
  2. We define a controller named 'CartController'.
  3. Inside the controller, we set up an empty array for our items and a total variable.
  4. We create functions to add items, remove items, and calculate the total.

Building the User Interface

Step 3: Creating the Item List

Let's update our HTML to display the items in our cart:

<body ng-controller="CartController">
<h1>My Shopping Cart</h1>
<ul>
<li ng-repeat="item in items">
{{item.name}} - ${{item.price}}
<button ng-click="removeItem($index)">Remove</button>
</li>
</ul>
<p>Total: ${{total}}</p>
</body>

Here, we're using AngularJS directives:

  • ng-repeat to loop through our items
  • {{}} for data binding to display item properties
  • ng-click to call our removeItem function when the button is clicked

Step 4: Adding New Items

Let's add a form to allow users to add new items:

<form ng-submit="addItem(newItem)">
<input type="text" ng-model="newItem.name" placeholder="Item name" required>
<input type="number" ng-model="newItem.price" placeholder="Price" required>
<button type="submit">Add to Cart</button>
</form>

This form uses:

  • ng-submit to call our addItem function when the form is submitted
  • ng-model to bind input values to our newItem object

Enhancing the Application

Step 5: Adding Item Quantities

Let's modify our application to handle item quantities:

app.controller('CartController', function($scope) {
// ... previous code ...

$scope.addItem = function(item) {
var existingItem = $scope.items.find(function(i) {
return i.name === item.name;
});

if (existingItem) {
existingItem.quantity += 1;
} else {
item.quantity = 1;
$scope.items.push(item);
}
$scope.calculateTotal();
$scope.newItem = {};
};

$scope.removeItem = function(index) {
var item = $scope.items[index];
item.quantity -= 1;
if (item.quantity === 0) {
$scope.items.splice(index, 1);
}
$scope.calculateTotal();
};

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

And update our HTML:

<li ng-repeat="item in items">
{{item.name}} - ${{item.price}} x {{item.quantity}}
<button ng-click="removeItem($index)">Remove</button>
</li>

Conclusion

Congratulations! You've just built a functional shopping cart application using AngularJS. We've covered the basics of setting up an AngularJS application, creating controllers, using directives for data binding and event handling, and even added some more advanced features like managing item quantities.

Remember, learning to code is a journey, and this is just the beginning. Keep practicing, experimenting, and most importantly, have fun with it!

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

Concept Description Example
Module Containers for different parts of an app angular.module('cartApp', [])
Controller Contains the business logic for a part of the app app.controller('CartController', function($scope) {...})
Scope Object that refers to the application model $scope.items = []
Directives Extend HTML with custom attributes and elements ng-repeat, ng-click, ng-submit
Data Binding Sync data between the model and the view {{item.name}}

Keep coding, and remember: every expert was once a beginner. You're doing great!

Credits: Image by storyset