To start using AngularJS, follow these steps to set up a basic project.
1. Download and Include AngularJS
Option 1: Using a CDN (Recommended for Quick Setup)
You can include AngularJS via a CDN by adding the following <script>
tag in your HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Setup</title>
</head>
<body ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<h1>AngularJS Setup Complete!</h1>
</body>
</html>
- This method is quick and easy, as it loads AngularJS directly from Google’s CDN.
- Make sure you have an internet connection to fetch the file.
Option 2: Download AngularJS Locally
- Download AngularJS
- Visit AngularJS Official Website
- Download the angular.min.js file.
- Include it in Your Project
- Place
angular.min.js
in your project folder. - Add the script in your HTML file:
<script src="angular.min.js"></script>
- Place
2. Creating a Basic AngularJS Application
Now, let’s create a simple AngularJS app.
Step 1: Define an AngularJS Module
In script.js
, define a new module:
var app = angular.module("myApp", []);
angular.module("myApp", [])
creates an AngularJS module named"myApp"
.- The empty array
[]
indicates no dependencies.
Step 2: Create a Controller
Add a controller inside script.js
:
app.controller("myController", function($scope) {
$scope.message = "Hello, AngularJS!";
});
$scope
is an object that connects HTML (view) and JavaScript (controller).
Step 3: Link Everything in HTML
Create an index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Setup</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<h1>{{ message }}</h1>
</div>
</body>
</html>
ng-app="myApp"
initializes the AngularJS application.ng-controller="myController"
binds the controller to the HTML.{{ message }}
displays themessage
value from$scope
.
3. Running the AngularJS App
- Simply open
index.html
in a browser (Chrome, Firefox, Edge, etc.). - You should see “Hello, AngularJS!” displayed.
4. Setting Up a Local Development Environment (Optional)
If you’re working on a larger project, use Node.js and a local server for better performance.
Step 1: Install Node.js
- Download and install Node.js from https://nodejs.org
Step 2: Install http-server
(Optional for Local Testing)
Run the following command:
npm install -g http-server
Step 3: Start the Server
Navigate to your project folder and run:
http-server
This will host your AngularJS project locally.