Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
AngularJS

AngularJS Complete Tutorial (99 Topics with ngRoute, $http & Final SPA)

Complete AngularJS 1.x tutorial covering modules, scope, directives, services, ngRoute, forms, $http REST, auth, and a final AngularJS single page application.

AngularJS Complete Tutorial (99 Topics with ngRoute, $http & Final SPA) — a practical guide to AngularJS tutorial with clear examples you can reuse in real projects.

This complete AngularJS (1.x) tutorial covers 99 topics — from modules and $scope to directives, ngRoute, $http, forms, and a final AngularJS single page application.

Course roadmap

1. Introduction to AngularJS

AngularJS (Angular 1.x) is a legacy JavaScript framework for SPAs with two-way binding and directives. This series covers setup, scope, directives, filters, services, ngRoute, forms, AJAX, auth, and a complete final AngularJS SPA. Prefer modern Angular for new greenfield apps; this path is ideal for maintaining or learning classic AngularJS apps.

  1. Include AngularJS and create a module.
  2. Practice scope, directives, and $http.
  3. Build the final AngularJS SPA.

Learning path

Setup + modules + controllers
Scope + binding + directives
Filters + services + DI
ngRoute SPA + forms
$http REST + auth
Final AngularJS SPA

2. What is AngularJS?

AngularJS extends HTML with directives and binds data via scopes and digest cycles.

AngularJS at a glance

JavaScript SPA framework (1.x)
Directives extend HTML
Two-way data binding
Dependency injection
Legacy — LTS/maintenance mindset

3. AngularJS Features

The digest/$watch model powers automatic UI updates when scope data changes.

Feature highlights

Two-way binding
Directives (ng-*)
Controllers + $scope
Services / factories
ngRoute SPAs
Filters

4. AngularJS vs Angular

Angular is a rewrite (TypeScript, components, RxJS) — not a drop-in upgrade from AngularJS.

Compare tip

AngularJS → JS, $scope, ng-*
Angular → TypeScript, components, signals/RxJS
Migration needs planning (ngUpgrade)
New apps: prefer modern Angular

5. AngularJS Architecture

Data flows through $scope (or controller-as) between views and logic.

Architecture

Module bootstraps app
Controllers bind view logic
Services hold shared logic
Directives manipulate DOM
Digest cycle updates bindings

6. Installing AngularJS

Pin a 1.8.x version for the last stable 1.x line when maintaining apps.

Install options

CDN script tag
Local angular.min.js
bower/npm legacy packages
Load angular.js before app.js

7. Including AngularJS in HTML

Put app scripts after angular.js so modules register correctly.

Include sketch

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<script src="app.js"></script>
<div ng-app="myApp">...</div>

8. Creating Your First AngularJS Application

Confirm the app name in ng-app matches angular.module(…).

  1. Add angular.min.js.
  2. Create a module and controller.
  3. Bind a value in the template.

Hello AngularJS

<div ng-app="helloApp" ng-controller="HelloCtrl as vm">
  <p>{{ vm.message }}</p>
</div>
<script>
  angular.module('helloApp', [])
    .controller('HelloCtrl', function () {
      this.message = 'Hello AngularJS';
    });
</script>

9. AngularJS Project Structure

Feature folders scale better than dumping everything in one file.

Structure tip

index.html
js/app.js
js/controllers/
js/services/
views/
css/

10. Modules in AngularJS

List dependencies (ngRoute, ngAnimate) in the dependency array.

Module

// create
angular.module('myApp', ['ngRoute']);
// retrieve later
angular.module('myApp').controller('HomeCtrl', HomeCtrl);

11. Controllers in AngularJS

Keep controllers thin — move reusable logic to services.

Controller

angular.module('myApp')
  .controller('ProductCtrl', function (ProductService) {
    var vm = this;
    vm.items = [];
    ProductService.list().then(function (items) {
      vm.items = items;
    });
  });

12. Scope in AngularJS

Child scopes prototypally inherit from parents; isolate scopes in directives differ.

Scope tip

$scope binds view ↔ controller
Scope hierarchy / inheritance
controller-as reduces $scope use
Avoid depending on $parent

13. $scope Object in AngularJS

Prefer controller-as (this / vm) in newer AngularJS style guides.

$scope example

angular.module('myApp')
  .controller('HelloCtrl', function ($scope) {
    $scope.name = 'Asha';
    $scope.greet = function () {
      return 'Hello ' + $scope.name;
    };
  });

14. Expressions in AngularJS

No control flow statements inside expressions; use directives instead.

Expressions

<p>{{ 1 + 2 }}</p>
<p>{{ user.name | uppercase }}</p>

15. Data Binding in AngularJS

Binding is powered by watchers evaluated during the digest cycle.

Binding types

Interpolation {{ }}
ng-bind
ng-model (two-way)
One-time binding {{ ::value }}

16. One-Way Data Binding in AngularJS

Use one-time binding {{ ::x }} when values won’t change (fewer watchers).

One-way

<h1 ng-bind="title"></h1>
<p>{{ ::staticLabel }}</p>

17. Two-Way Data Binding in AngularJS

Classic AngularJS strength — also a performance cost if overused.

Two-way

<input ng-model="user.name" />
<p>Hello {{ user.name }}</p>

18. ng-model in AngularJS

Works with input, select, and textarea; drives form validation state.

ng-model

<input type="email" ng-model="form.email" name="email" required />

19. ng-bind in AngularJS

Useful for SEO/UX when templates briefly show raw braces.

ng-bind

<span ng-bind="message"></span>

20. ng-init in AngularJS

Prefer initializing in controllers for testable code.

ng-init

<div ng-init="count = 0">
  <p>{{ count }}</p>
</div>

21. AngularJS Directives

Directives are the heart of AngularJS view composition.

Directive idea

Built-in ng-* directives
Custom element/attribute directives
Isolate scope + templates
Link / compile functions

22. Built-in Directives in AngularJS

Learn ng-app, ng-repeat, ng-if, and event directives first.

Built-in list

ng-app, ng-controller
ng-repeat, ng-if, ng-show
ng-class, ng-style
ng-click, ng-submit
ng-options

23. ng-app in AngularJS

Only one ng-app per page unless you manual-bootstrap extras.

ng-app

<body ng-app="myApp">
  <!-- app root -->
</body>

24. ng-controller in AngularJS

controller as vm improves clarity versus bare $scope.

ng-controller

<div ng-controller="CartCtrl as cart">
  <p>{{ cart.total }}</p>
</div>

25. ng-repeat in AngularJS

Use track by to avoid DOM thrashing when collections refresh.

ng-repeat

<li ng-repeat="item in items track by item.id">
  {{ item.name }}
</li>

26. ng-if in AngularJS

Unlike ng-show, ng-if destroys scope/DOM when false.

ng-if

<p ng-if="user">Welcome {{ user.name }}</p>
<p ng-if="!user">Please log in</p>

27. ng-show and ng-hide in AngularJS

Elements stay in the DOM — watchers may still run.

ng-show

<div ng-show="isOpen">Panel</div>
<div ng-hide="isLoading">Content</div>

28. ng-switch in AngularJS

Combine ng-switch-when and ng-switch-default.

ng-switch

<div ng-switch="tab">
  <div ng-switch-when="home">Home</div>
  <div ng-switch-when="about">About</div>
  <div ng-switch-default>Other</div>
</div>

29. ng-class in AngularJS

Prefer class toggles over heavy ng-style for theme states.

ng-class

<div ng-class="{ active: isOn, disabled: !isOn }">Panel</div>

30. ng-style in AngularJS

Use sparingly; classes are usually cleaner.

ng-style

<p ng-style="{ color: textColor, fontSize: size + 'px' }">Text</p>

31. Custom Directives in AngularJS

Use isolate scope bindings (@, =, &) for reusable APIs.

Directive sketch

angular.module('myApp').directive('appAlert', function () {
  return {
    restrict: 'E',
    scope: { message: '@' },
    template: '<div class="alert">{{ message }}</div>'
  };
});

32. AngularJS Events

You can also bind native events carefully inside directives.

Events tip

ng-click / ng-change / ng-submit
ng-mouseenter / ng-keyup
$event object available
Prefer methods on vm/$scope

33. ng-click in AngularJS

Pass $event when you need preventDefault.

ng-click

<button ng-click="vm.save($event)">Save</button>

34. ng-change in AngularJS

Requires ng-model on the same control.

ng-change

<select ng-model="vm.city" ng-change="vm.loadAreas()">...</select>

35. ng-submit in AngularJS

Pairs with form validation flags before calling APIs.

ng-submit

<form name="contactForm" ng-submit="vm.send(contactForm)" novalidate>
  <!-- fields -->
  <button type="submit">Send</button>
</form>

36. Mouse and Keyboard Events in AngularJS

For complex gestures, custom directives may be cleaner.

Events

<input ng-keyup="vm.onType($event)" />
<div ng-mouseenter="vm.hover = true" ng-mouseleave="vm.hover = false">...</div>

37. AngularJS Filters

Filters can also be injected and used in JavaScript.

Filter idea

{{ price | currency }}
{{ title | uppercase }}
{{ items | filter:query }}

38. Built-in Filters in AngularJS

orderBy/filter on large lists can be expensive — precompute when needed.

Built-in tip

{{ createdAt | date:'medium' }}
<li ng-repeat="i in items | orderBy:'name' | limitTo:10">

39. Custom Filters in AngularJS

Keep filters pure/fast — they may run often during digests.

Custom filter

angular.module('myApp').filter('truncate', function () {
  return function (value, limit) {
    limit = limit || 20;
    value = value || '';
    return value.length > limit ? value.slice(0, limit) + '…' : value;
  };
});

40. Services in AngularJS

Services are singletons within an injector / module.

Service types

service()
factory()
provider()
value() / constant()
Built-ins: $http, $timeout, $q

41. $http Service in AngularJS

Configure defaults with $httpProvider for headers and interceptors.

$http GET

$http.get('/api/items').then(function (res) {
  vm.items = res.data;
}, function (err) {
  vm.error = 'Failed to load';
});

42. $location Service in AngularJS

Works with HTML5 mode or hashbang URL strategies.

$location tip

$location.path('/products');
$location.search('page', 2);
var page = $location.search().page;

43. $timeout Service in AngularJS

Prefer $timeout over raw setTimeout so bindings update.

$timeout

$timeout(function () {
  vm.saved = false;
}, 2000);

44. $interval Service in AngularJS

Always cancel intervals to avoid leaks.

$interval

var tick = $interval(function () {
  vm.now = new Date();
}, 1000);
$scope.$on('$destroy', function () {
  $interval.cancel(tick);
});

45. Creating Custom Services in AngularJS

Inject $http and other deps via array annotations for minification safety.

service()

angular.module('myApp').service('ItemService', ['$http', function ($http) {
  this.list = function () {
    return $http.get('/api/items').then(function (res) { return res.data; });
  };
}]);

46. Factories in AngularJS

Factories are often preferred for revealing-module style APIs.

factory()

angular.module('myApp').factory('ItemApi', ['$http', function ($http) {
  return {
    list: function () { return $http.get('/api/items'); }
  };
}]);

47. Providers in AngularJS

Only providers/constants are available in angular.module.config.

provider tip

config blocks use providers
$httpProvider / $routeProvider
Custom provider for configurable APIs
factory/service are shortcuts

48. Dependency Injection in AngularJS

Implicit annotation breaks when parameter names are mangled.

DI annotation

HomeCtrl.$inject = ['$scope', 'ItemService'];
function HomeCtrl($scope, ItemService) { /* ... */ }

49. AngularJS Routing

ngRoute is the official simple router; ui-router is a popular alternative.

Routing tip

ngRoute module
$routeProvider.when
ng-view outlet
deep-linking URLs

50. ngRoute in AngularJS

Place <div ng-view></div> where templates should render.

ngRoute setup

<script src="angular-route.min.js"></script>
<div ng-app="myApp" ng-view></div>

51. Route Configuration in AngularJS

Use templateUrl + controller / controllerAs for each route.

$routeProvider

angular.module('myApp').config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when('/', { templateUrl: 'views/home.html', controller: 'HomeCtrl', controllerAs: 'vm' })
    .when('/items/:id', { templateUrl: 'views/item.html', controller: 'ItemCtrl', controllerAs: 'vm' })
    .otherwise({ redirectTo: '/' });
}]);

52. Route Parameters in AngularJS

Watch $routeUpdate or reloadOnSearch settings for query changes.

$routeParams

angular.module('myApp').controller('ItemCtrl', ['$routeParams', 'ItemService', function ($routeParams, ItemService) {
  var vm = this;
  ItemService.get($routeParams.id).then(function (item) { vm.item = item; });
}]);

53. Multiple Views in AngularJS

ngRoute supports one ng-view; ui-router unlocks multiple named views.

Multiple views tip

ng-include for partials
ngRoute = single ng-view
ui-router for complex layouts
Shared header/footer outside ng-view

54. Single Page Applications with AngularJS

Manage auth, loading states, and deep links carefully.

SPA checklist

Client routing
Shared layout shell
API-driven data
History / bookmarkable URLs
Central error/auth handling

55. Templates in AngularJS

Cache templates with $templateCache for production performance.

Template tip

views/*.html partials
template vs templateUrl
$templateCache
Keep templates declarative

56. Form Handling in AngularJS

Name the form to access $valid / $dirty state on scope.

Form tip

<form name="signupForm" ng-submit="vm.register(signupForm)" novalidate>
  <input name="email" ng-model="vm.email" required />
  <button ng-disabled="signupForm.$invalid">Register</button>
</form>

57. Form Validation in AngularJS

Always re-validate on the server for security.

Validation UX

<p ng-show="signupForm.email.$touched && signupForm.email.$invalid">
  Enter a valid email.
</p>

58. Built-in Validators in AngularJS

Each adds keys under control.$error.

Validators

<input ng-model="vm.username"
       required
       ng-minlength="3"
       ng-pattern="/^[a-z0-9]+$/" />

59. Custom Form Validation in AngularJS

Useful for unique username checks and domain rules.

Custom validator tip

require: 'ngModel'
parsers/formatters
$setValidity('rule', boolean)
Async validation with $http

60. $valid, $invalid, $dirty and $pristine in AngularJS

$touched/$untouched help show errors after blur.

Form states

$valid / $invalid
$dirty / $pristine
$touched / $untouched
$submitted (form)

61. AJAX with AngularJS

Show loading flags around promise lifecycles.

AJAX tip

$http / $resource
Promises (.then)
Loading & error UI
JSON APIs

62. REST API Integration in AngularJS

Keep base URLs configurable for environments.

REST factory tip

return {
  list: function () { return $http.get(base + '/items'); },
  save: function (item) { return $http.post(base + '/items', item); }
};

63. GET Requests in AngularJS

Handle empty lists and 404s in the error path.

GET

$http.get('/api/items', { params: { q: query } })
  .then(function (res) { vm.items = res.data; });

64. POST Requests in AngularJS

Set Content-Type when talking to strict APIs.

POST

$http.post('/api/items', { name: vm.name })
  .then(function (res) { vm.created = res.data; });

65. PUT Requests in AngularJS

Include the resource id in the URL.

PUT

$http.put('/api/items/' + id, vm.item);

66. DELETE Requests in AngularJS

Confirm destructive actions in the UI first.

DELETE

$http.delete('/api/items/' + id)
  .then(function () { vm.refresh(); });

67. JSON Data Handling in AngularJS

angular.toJson / fromJson helpers exist for manual cases.

JSON tip

var payload = angular.toJson(vm.form);
var obj = angular.fromJson(jsonString);

68. Promises in AngularJS

$http returns promises; compose them instead of nesting callbacks.

Promise tip

ItemService.list()
  .then(function (items) { vm.items = items; return items[0]; })
  .then(function (first) { return ItemService.get(first.id); });

69. $q Service in AngularJS

$q.all waits for parallel tasks; $q.reject for errors.

$q tip

var deferred = $q.defer();
// deferred.resolve(value) / deferred.reject(err)
return deferred.promise;

70. Error Handling in AngularJS

Global $http interceptors can normalize API errors.

Error tip

$http.get('/api/items').then(success, function (err) {
  vm.error = (err.data && err.data.message) || 'Request failed';
});

71. Authentication in AngularJS

Prefer httpOnly cookies when possible; tokens in storage have XSS risk.

Auth pieces

Login/register UI
Auth service singleton
$http interceptor for tokens
Route resolve / redirects
Logout clears state

72. Login and Registration in AngularJS

Disable submit while $invalid or request in flight.

Auth form tip

ng-model credentials
ng-submit → AuthService.login
Store token/session
$location.path('/dashboard')

73. Token-Based Authentication in AngularJS

Clear tokens on 401 and redirect to login.

Interceptor tip

$httpProvider.interceptors.push(function ($q, $injector) {
  return {
    request: function (config) {
      var token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    }
  };
});

74. Local Storage in AngularJS

Libraries like angular-local-storage exist; a thin factory often suffices.

localStorage tip

localStorage.setItem('theme', 'dark');
var theme = localStorage.getItem('theme');

75. Session Management in AngularJS

Handle expiry, logout, and multi-tab consistency.

Session tip

AuthService holds currentUser
Bootstrap: read token → profile
401 → clear session
Optional sessionStorage for tab scope

76. AngularJS Animations

Include angular-animate and ngAnimate module dependency.

ngAnimate tip

angular-animate.js
ngAnimate dependency
CSS classes ng-enter / ng-leave
Prefer subtle transitions

77. AngularJS and Bootstrap

Avoid conflicting jQuery plugins that fight the digest cycle.

Bootstrap tip

Bootstrap CSS grid
ui-bootstrap components
ng-class for active nav
Forms + validation classes

78. AngularJS with PHP

Return application/json; validate/sanitize on the server.

PHP JSON tip

header('Content-Type: application/json');
echo json_encode(['items' => $items]);

79. AngularJS with MySQL

Use prepared statements server-side; send only JSON to the browser.

Architecture

AngularJS $http
  → PHP/Node API
    → MySQL
  ← JSON
← Update $scope/vm

80. AngularJS with Node.js

Enable CORS carefully in development; same-origin in production proxies.

Node tip

Express JSON routes
Static SPA hosting
JWT auth optional
Proxy /api in dev

81. AngularJS with Laravel

Use Laravel Sanctum/Passport patterns for API auth as appropriate.

Laravel tip

routes/api.php JSON
CSRF for cookie/spa mode
CORS config
Resource controllers

82. AngularJS with WordPress

Enqueue scripts properly; localize REST URL and nonces when needed.

WP tip

wp_enqueue_script
wp-api / REST nonce
Application passwords / JWT plugins
Keep admin/public contexts clear

83. AngularJS REST API Integration Deep Dive

Version your API base path and map DTOs consistently.

Integration checklist

Base URL config
Resource factories
Auth interceptor
Error normalization
Loading state service

84. Custom Components in AngularJS

Components default to isolate scope and controller-as $ctrl.

component()

angular.module('myApp').component('userCard', {
  bindings: { user: '<' },
  templateUrl: 'views/user-card.html',
  controller: function () {
    var $ctrl = this;
  }
});

85. Reusable Components in AngularJS

Document inputs/outputs; avoid reaching into parent scopes.

Reuse tip

Isolate bindings
One-way < for inputs
& for callbacks
Dumb presentational components

86. AngularJS Performance Optimization

Profile digest times; paginate large lists.

Perf checklist

Fewer watchers
{{ ::oneTime }}
track by in ng-repeat
Debounce inputs
Pagination / virtualization
Avoid filters in hot loops

87. Digest Cycle in AngularJS

Infinite digests usually mean unstable model updates inside watchers.

Digest tip

$apply → $digest
Watchers compared old/new
TTL (~10) then error
Keep watchers cheap

88. $watch in AngularJS

Deep watches (objectEquality true) are expensive — use carefully.

$watch

var off = $scope.$watch('vm.query', function (nv, ov) {
  if (nv !== ov) { vm.search(nv); }
});
$scope.$on('$destroy', off);

89. $apply in AngularJS

Needed after raw DOM events or third-party callbacks.

$apply

$scope.$apply(function () {
  $scope.message = 'Updated from outside';
});

90. $digest in AngularJS

$apply wraps your function and calls $digest on $rootScope.

$digest tip

$digest = run watchers
$apply = eval + digest from root
Prefer $apply for external updates
Don't call $digest casually in app code

91. Debugging AngularJS Applications

angular.element(el).scope() helps inspect scope in non-production builds.

Debug tip

// in console (non-minified / debug friendly)
angular.element(document.querySelector('[ng-controller]')).scope();

92. AngularJS Security Best Practices

AngularJS expression sandbox was not a security boundary — sanitize server-side.

Security checklist

Prefer ng-bind / {{ }} over HTML injection
Sanitize ng-bind-html input
CSRF tokens on cookie auth
Don't trust client-only authZ
Keep AngularJS patched (1.8.x)

93. Testing AngularJS Applications

Mock $httpBackend to assert API interactions.

Testing tip

angular-mocks
module() / inject()
$httpBackend.expectGET
Component/controller specs
Karma runner

94. Unit Testing with Jasmine in AngularJS

Inject dependencies with angular-mocks inject().

Jasmine tip

describe('truncate filter', function () {
  beforeEach(module('myApp'));
  it('truncates', inject(function ($filter) {
    expect($filter('truncate')('Hello World', 5)).toBe('Hello…');
  }));
});

95. Karma Testing for AngularJS

Configure files to load angular, angular-mocks, then app + specs.

Karma tip

karma.conf.js file list
Browsers: ChromeHeadless
singleRun in CI
Coverage optional

96. AngularJS Project Structure Best Practices

John Papa style guide patterns remain useful for AngularJS codebases.

Best practices

Feature folders
controllerAs
Array DI annotations
Thin controllers
$http in services
Avoid $scope soup

97. AngularJS Interview Questions

Be ready for digest/$watch, directives, DI annotation, and ngRoute.

Sample Q&A

Q: ng-if vs ng-show?
A: ng-if removes DOM/scope; ng-show toggles CSS display.

Q: Why array DI annotation?
A: Survives minification when parameter names change.

Q: What is digest?
A: Loop that evaluates watchers until stable.

98. Real-World AngularJS Project

Include ngRoute, forms validation, and $http error states.

Project ideas

Todo SPA + localStorage
Contacts CRUD + PHP API
Product catalog filters
Simple dashboard charts
Login-gated notes app

99. Final Project – Complete AngularJS Single Page Application

Ship a production-shaped SPA (e.g., task manager or notes): module + ngRoute, controller-as components, validated forms, $http CRUD against a JSON API (PHP/Node/mock), auth + interceptor optional, loading/error/empty states, basic Jasmine tests, and a README.

  1. Scaffold module, routes, and layout.
  2. Implement CRUD services and forms.
  3. Add validation, states, and optional auth.
  4. Test, document, and polish the SPA.

Final project scope

1. index.html + angular + ngRoute
2. Module + route config + ng-view
3. Feature controllers (controllerAs)
4. Services/factories for API
5. List + detail + create/edit forms
6. Form validation UX
7. Loading/error/empty states
8. Optional auth + token interceptor
9. Jasmine + $httpBackend tests
10. README with run steps

Suggested structure

index.html
js/app.js
js/controllers/
js/services/
views/
tests/
api/ (optional PHP/Node)

Conclusion

You now have a full AngularJS 1.x path: modules, scope, directives, services, routing, and AJAX. Finish the final AngularJS SPA to turn the lessons into a maintainable classic front-end project.

Leave a reply

Your email address will not be published. Required fields are marked *