Published on August 29, 2024By DeveloperBreeze

Full AngularJS Tutorial: Building a Web Application from Scratch

AngularJS, developed and maintained by Google, is a powerful JavaScript-based framework for building dynamic web applications. Although AngularJS has been succeeded by Angular (commonly referred to as Angular 2+), it remains a popular choice for maintaining and extending legacy applications.

This tutorial will guide you through building a simple web application using AngularJS, covering the essential concepts, features, and best practices.

---

1. Introduction to AngularJS

What is AngularJS?

AngularJS is a structural framework for dynamic web applications. It allows you to use HTML as your template language and extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write.

Key Features:

- Two-Way Data Binding: Synchronizes data between the model and the view.

  • Directives: Extend HTML with custom attributes and elements.

  • Dependency Injection: Provides a built-in dependency injection mechanism.

  • MVC Architecture: Encourages separation of concerns via the Model-View-Controller (MVC) design pattern.

  • Routing: Built-in support for deep linking and routing.

---

2. Setting Up the Environment

Step 1: Install AngularJS

You can download AngularJS from [AngularJS.org](https://angularjs.org/) or include it directly in your HTML file via a CDN:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

Step 2: Create a Project Directory

Create a new directory for your project and include an index.html file where you will write your code.

Project Structure:

my-angular-app/
├── index.html
├── app.js
└── style.css

---

3. Creating Your First AngularJS Application

Step 1: Basic HTML Structure

In index.html, start with a basic HTML structure and include the AngularJS script:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>My AngularJS App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Welcome to My AngularJS App</h1>
    <div ng-controller="MainController">
        <h2>{{ title }}</h2>
        <p>{{ description }}</p>
    </div>
</body>
</html>

ng-app="myApp": Defines the root element of the AngularJS application.

ng-controller="MainController": Attaches a controller to the specified element.

Step 2: Create the AngularJS Application

In app.js, define your AngularJS module and controller:

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

app.controller('MainController', function($scope) {
    $scope.title = "Hello, AngularJS!";
    $scope.description = "This is a simple AngularJS application.";
});

angular.module('myApp', []): Creates a new AngularJS module named myApp.

$scope: The binding part between HTML (view) and JavaScript (controller). It is the object that holds model data.

---

4. Understanding Directives

AngularJS directives are special attributes starting with ng- that are added to HTML elements to extend their functionality.

Commonly Used Directives:

ng-model: Binds the value of HTML controls (input, select, textarea) to application data.

<input type="text" ng-model="name">
<p>Hello, {{ name }}!</p>

ng-repeat: Loops through an array or object to generate repeated elements.

<ul>
    <li ng-repeat="item in items">{{ item }}</li>
</ul>

ng-if: Conditionally includes an element based on the expression.

<p ng-if="showMessage">This message is visible.</p>

ng-click: Binds an expression to the click event of an element.

<button ng-click="clickMe()">Click Me</button>

Example:

In app.js:

app.controller('MainController', function($scope) {
    $scope.title = "AngularJS Directives";
    $scope.items = ['Item 1', 'Item 2', 'Item 3'];
    $scope.showMessage = true;
    $scope.clickMe = function() {
        alert('Button clicked!');
    };
});

In index.html:

<h2>{{ title }}</h2>
<ul>
    <li ng-repeat="item in items">{{ item }}</li>
</ul>
<p ng-if="showMessage">This is a conditional message.</p>
<button ng-click="clickMe()">Click Me</button>

---

5. Two-Way Data Binding

Two-way data binding is a core feature of AngularJS that keeps the model and the view in sync. Changes to the model automatically update the view, and vice versa.

Example:

In app.js:

app.controller('MainController', function($scope) {
    $scope.user = {
        firstName: 'John',
        lastName: 'Doe'
    };
});

In index.html:

<h2>User Profile</h2>
<p>First Name: <input type="text" ng-model="user.firstName"></p>
<p>Last Name: <input type="text" ng-model="user.lastName"></p>
<p>Full Name: {{ user.firstName }} {{ user.lastName }}</p>

This simple example shows how changes in the input fields automatically reflect in the paragraph displaying the full name, demonstrating two-way data binding.

---

6. Working with Forms

AngularJS simplifies form handling with built-in directives and validation mechanisms.

Example:

In app.js:

app.controller('FormController', function($scope) {
    $scope.user = {};
    $scope.submitForm = function() {
        alert('Form submitted! Name: ' + $scope.user.name);
    };
});

In index.html:

<div ng-controller="FormController">
    <form ng-submit="submitForm()">
        <label>Name:</label>
        <input type="text" ng-model="user.name" required>
        <br>
        <label>Email:</label>
        <input type="email" ng-model="user.email" required>
        <br>
        <button type="submit">Submit</button>
    </form>
</div>

ng-submit: Binds an expression to the form’s submit event.

ng-model: Binds the input field to the model (in this case, user.name and user.email).

AngularJS also automatically validates forms based on the input type (e.g., email, required).

---

7. Services and Dependency Injection

Services in AngularJS are singleton objects or functions that carry out specific tasks. They can be injected into controllers, directives, or other services using dependency injection.

Creating a Service:

app.service('DataService', function() {
    this.getData = function() {
        return ['Apple', 'Banana', 'Cherry'];
    };
});

Using a Service in a Controller:

app.controller('MainController', function($scope, DataService) {
    $scope.items = DataService.getData();
});

app.service: Defines a service.

  • Dependency Injection: The DataService is injected into the MainController.

---

8. Routing with ngRoute

AngularJS provides a module called ngRoute to enable routing, allowing you to build single-page applications (SPAs).

Step 1: Include ngRoute in Your Project:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js"></script>

Step 2: Configure Routes:

In app.js:

app.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: 'home.html',
        controller: 'HomeController'
    })
    .when('/about', {
        templateUrl: 'about.html',
        controller: 'AboutController'
    })
    .otherwise({
        redirectTo: '/'
    });
});

app.controller('HomeController', function($scope) {
    $scope.message = "Welcome to the Home Page!";
});

app.controller('AboutController', function($scope) {
    $scope.message = "Welcome to the About Page!";
});

Step 3: Create View Templates:

home.html:

<h2>{{ message }}</h2>
<p>This is the home page content.</p>

about.html:

<h2>{{ message }}</h2>
<p>This is the about page content.</p>

Step 4: Add the ng-view Directive:

In index.html:

<div ng-view></div>

  • **ng-view </li></ul></p> <p>**: Acts as a placeholder for the view templates based on the current route.

    This setup enables navigation between different views without reloading the page.

    ---

    9. Custom Directives

    Custom directives in AngularJS allow you to encapsulate and reuse HTML and behavior across your application.

    Example:

    In app.js:

    app.directive('customMessage', function() {
        return {
            restrict: 'E',
            template: '<h3>This is a custom directive!</h3>'
        };
    });
    

    In index.html:

    <custom-message></custom-message>
    

    restrict: 'E': Specifies that the directive will be used as an element.

    template: Defines the HTML template for the directive.

    Custom directives can also include their own controllers, scope, and complex behaviors.

    ---

    10. Best Practices

      • Modularize Your Application: Break your application into modules to make it more maintainable and scalable.

      • Use Controllers and Services Appropriately: Keep controllers focused on managing scope and delegate logic to services.

      • Leverage Dependency Injection: Make your code more modular and testable by using AngularJS’s built-in dependency injection.

      • Use ng-bind Instead of {{ }}: Prevent flickering by using ng-bind to bind data to elements.

      • Keep the DOM Clean with Directives: Use directives to encapsulate behavior and reduce duplication in your HTML.

    ---

    11. Conclusion

    AngularJS is a powerful framework that allows you to build dynamic, single-page applications with ease. With features like two-way data binding, dependency injection, and modular architecture, AngularJS enables developers to create maintainable and scalable applications. By following this tutorial, you’ve learned how to set up an AngularJS project, work with controllers, services, routing, and custom directives, and follow best practices for developing in AngularJS.

    While AngularJS may not be the latest in the Angular family, it remains a valuable tool for maintaining legacy projects or building applications where its specific strengths shine.

Comments

Please log in to leave a comment.