Session 6.3 – AngularJS Fundamentals

Module 6: Advanced Technologies | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Understand the fundamentals of AngularJS framework
  • Implement two-way data binding in AngularJS applications
  • Work with built-in directives and create custom directives
  • Create and use controllers to manage application logic
  • Understand the concept of scope and its hierarchy
  • Use expressions and filters to manipulate data

Introduction to AngularJS

AngularJS (Angular 1.x) is a structural framework for dynamic web applications. It lets you use HTML as your template language and extends HTML's syntax to express your application's components clearly and succinctly.

What is AngularJS?

AngularJS is a JavaScript-based open-source front-end web framework developed by Google in 2010. It simplifies both the development and testing of web applications by providing a framework for client-side MVC and MVVM architectures.

Two-Way Binding

Automatic synchronization between model and view

Dependency Injection

Built-in dependency injection system

Directives

Extend HTML with custom attributes and elements

Core Concepts of AngularJS

1. Modules

Modules are containers for different parts of your application. They help organize code and manage dependencies.

// Creating an AngularJS module
var app = angular.module('myApp', []);

// Module with dependencies
var app = angular.module('myApp', ['ngRoute', 'ngResource']);
2. Controllers

Controllers control the data flow and handle user interactions in AngularJS applications.

// Creating a controller
app.controller('MainController', function($scope) {
    $scope.message = 'Hello, AngularJS!';
    $scope.items = ['Item 1', 'Item 2', 'Item 3'];
});
3. Views

Views are HTML templates with AngularJS-specific markup and directives.

<!-- HTML View -->
<div ng-app="myApp" ng-controller="MainController">
    <h1>{{ message }}</h1>
    <ul>
        <li ng-repeat="item in items">{{ item }}</li>
    </ul>
</div>
4. Services

Services are reusable business logic components that can be injected into controllers and other services.

// Creating a service
app.service('DataService', function() {
    this.getData = function() {
        return ['Data 1', 'Data 2', 'Data 3'];
    };
});

Two-Way Data Binding

One of the most powerful features of AngularJS is two-way data binding. Changes in the model automatically update the view, and changes in the view update the model.

How Two-Way Binding Works
View to Model

When user types in an input field, the model is automatically updated.

Model to View

When the model changes programmatically, the view is automatically updated.

<!-- HTML -->
<div ng-app="myApp" ng-controller="BindingController">
    <!-- Input field bound to model -->
    <input type="text" ng-model="username" placeholder="Enter name">

    <!-- Display automatically updates -->
    <p>Hello, {{ username }}!</p>

    <!-- Button to change model -->
    <button ng-click="changeName()">Change Name</button>
</div>

// JavaScript
app.controller('BindingController', function($scope) {
    $scope.username = 'John';

    $scope.changeName = function() {
        $scope.username = 'Jane';
    };
});
Live Example Concept

When you type in the input field:

  1. AngularJS detects the change
  2. Updates the $scope.username model
  3. Automatically updates all bindings in the view
  4. The greeting message updates in real-time

AngularJS Directives

Directives are markers on DOM elements that tell AngularJS to attach specific behavior to that element or transform the DOM element and its children.

ng-app

Defines the root element of an AngularJS application.

<html ng-app="myApp">
    <!-- AngularJS app starts here -->
</html>
ng-model

Binds an input, select, or textarea value to a property on the scope.

<input type="text" ng-model="name">
<p>You entered: {{ name }}</p>
ng-repeat

Iterates over a collection and instantiates a template for each item.

<ul>
    <li ng-repeat="user in users">
        {{ user.name }} - {{ user.email }}
    </li>
</ul>
ng-show / ng-hide

Shows or hides an element based on a boolean expression.

<div ng-show="isVisible">This is visible</div>
<div ng-hide="isHidden">This is hidden</div>
ng-if

Removes or recreates a portion of the DOM tree based on an expression.

<div ng-if="user.isAdmin">
    <button>Admin Panel</button>
</div>
ng-click

Specifies custom behavior when an element is clicked.

<button ng-click="count = count + 1">Increment</button>
<p>Count: {{ count }}</p>
ng-class

Dynamically adds or removes CSS classes.

<div ng-class="{ 'active': isActive, 'disabled': isDisabled }">
    Dynamic Classes
</div>

Controllers in AngularJS

Controllers are JavaScript functions that augment the AngularJS scope. They are used to set up the initial state and add behavior to the scope.

// Simple Controller
app.controller('UserController', function($scope) {
    // Initialize data
    $scope.user = {
        name: 'John Doe',
        email: 'john@example.com',
        age: 30
    };

    // Add methods
    $scope.updateUser = function() {
        $scope.user.name = 'Jane Doe';
    };

    $scope.resetUser = function() {
        $scope.user = {
            name: '',
            email: '',
            age: 0
        };
    };
});

// Controller with Dependency Injection
app.controller('ProductController', ['$scope', '$http',
    function($scope, $http) {
        $scope.products = [];

        // Load products from API
        $http.get('/api/products')
            .then(function(response) {
                $scope.products = response.data;
            })
            .catch(function(error) {
                console.error('Error loading products', error);
            });
    }
]);
Controller Best Practices
  • Use controllers to set up initial state of the scope
  • Use controllers to add behavior to the scope
  • Don't use controllers to manipulate DOM (use directives instead)
  • Don't use controllers to filter output (use filters instead)
  • Don't share code across controllers (use services instead)

Understanding Scope

The scope is the glue between the application controller and the view. It is an object that refers to the application model and provides an execution context for expressions.

Scope Hierarchy

AngularJS creates a hierarchy of scopes that mirrors the DOM structure.

<!-- Parent Scope -->
<div ng-controller="ParentController">
    <p>Parent: {{ parentValue }}</p>

    <!-- Child Scope -->
    <div ng-controller="ChildController">
        <p>Child: {{ childValue }}</p>
        <p>Parent from child: {{ parentValue }}</p>
    </div>
</div>
$rootScope

The root scope is the parent of all other scopes. Variables attached to $rootScope are available throughout the application.

app.run(function($rootScope) {
    $rootScope.appName = 'My AngularJS App';
    $rootScope.version = '1.0.0';
});
$scope Methods
  • $watch: Observes changes to a scope property
  • $apply: Executes an expression in the AngularJS context
  • $broadcast: Dispatches an event downwards to child scopes
  • $emit: Dispatches an event upwards to parent scopes
// Watch for changes
$scope.$watch('username', function(newValue, oldValue) {
    console.log('Username changed from ' + oldValue + ' to ' + newValue);
});

// Broadcast event
$scope.$broadcast('userLoggedIn', { userId: 123 });

AngularJS Expressions

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}.

<!-- Simple expressions -->
<p>{{ 5 + 5 }}</p>                    <!-- 10 -->
<p>{{ firstName + ' ' + lastName }}</p>

<!-- Object expressions -->
<p>{{ user.name }}</p>
<p>{{ user.address.city }}</p>

<!-- Array expressions -->
<p>{{ items[0] }}</p>
<p>{{ items.length }}</p>

<!-- Conditional expressions -->
<p>{{ age >= 18 ? 'Adult' : 'Minor' }}</p>
Expressions vs JavaScript
Similarities
  • Can contain literals, operators, and variables
  • Evaluated against a scope
  • Support ternary operators
Differences
  • No control flow statements (if, for, while)
  • No function declarations
  • Forgiving to undefined and null
  • No loops or exceptions

AngularJS Filters

Filters format the value of an expression for display to the user. They can be used in view templates, controllers, or services.

uppercase / lowercase
<p>{{ 'hello' | uppercase }}</p>  <!-- HELLO -->
<p>{{ 'WORLD' | lowercase }}</p>  <!-- world -->
currency
<p>{{ 99.99 | currency }}</p>
<!-- $99.99 -->
date
<p>{{ today | date:'fullDate' }}</p>
<p>{{ today | date:'yyyy-MM-dd' }}</p>
filter
<li ng-repeat="item in items | filter:searchText">
    {{ item }}
</li>
orderBy
<li ng-repeat="user in users | orderBy:'name'">
    {{ user.name }}
</li>
limitTo
<li ng-repeat="item in items | limitTo:5">
    {{ item }}
</li>
Creating Custom Filters
// Custom filter to reverse a string
app.filter('reverse', function() {
    return function(input) {
        if (!input) return '';
        return input.split('').reverse().join('');
    };
});

// Usage in view
<p>{{ 'hello' | reverse }}</p>  <!-- olleh -->

Session Summary

Key Points
  • AngularJS: Structural framework for dynamic web applications developed by Google
  • Two-Way Binding: Automatic synchronization between model and view
  • Directives: Extend HTML with custom attributes (ng-app, ng-model, ng-repeat, etc.)
  • Controllers: JavaScript functions that control data flow and user interactions
  • Scope: Glue between controller and view, provides execution context
  • Expressions: JavaScript-like code snippets in double curly braces
  • Filters: Format data for display (uppercase, currency, date, filter, orderBy)
Next Session Preview

In the next session, we will explore AngularJS Application Development, including routing, services, dependency injection, and building complete single-page applications.