Tuesday, 31 March 2015

AngularJS vs Angular

🔹 What is AngularJS?

AngularJS is a JavaScript framework developed by Google for building dynamic, single-page applications (SPAs). It extends HTML with additional attributes and binds data to HTML using expressions.


🔹 1. AngularJS Core Concepts

➤ a. Modules

A module defines the main application container.

js
var app = angular.module('myApp', []);
  • 'myApp' is the application name.

  • [] is where dependencies (like routing) go.


➤ b. Controllers

Controllers are JavaScript functions attached to parts of the HTML to control the data.

js
app.controller('MainController', function($scope) { $scope.message = "Hello from controller!"; });
html
<div ng-controller="MainController"> {{ message }} </div>

➤ c. Directives

Special HTML attributes prefixed with ng-. Examples:

DirectivePurposeExample
ng-appBootstraps Angular<html ng-app="myApp">
ng-modelBinds input to variable<input ng-model="name" />
ng-bindBinds data to element<span ng-bind="name"></span>
ng-controllerDefines controller scope<div ng-controller="MyCtrl">
ng-clickClick event handler<button ng-click="sayHi()">Click</button>
ng-repeatLoops through collections<li ng-repeat="item in list">{{ item }}</li>

➤ d. Two-Way Data Binding

Changes in the view update the model, and vice versa.

html
<input ng-model="name"> <h2>Hello {{ name }}</h2>

➤ e. Expressions

AngularJS expressions are written inside {{ }}.

html
{{ 5 + 5 }} <!-- 10 --> {{ name.toUpperCase() }} <!-- JOHN -->

🔹 2. Example: Hello World AngularJS App

📄 index.html

<!DOCTYPE html> <html ng-app="helloApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="HelloController"> <h1>{{ greeting }}</h1> <input ng-model="greeting"> </div> </body> </html>

📄 app.js

var app = angular.module('helloApp', []); app.controller('HelloController', function($scope) { $scope.greeting = "Hello AngularJS!"; });

🔹 3. Forms and Validation

AngularJS provides built-in form validation.

html
<form name="myForm"> <input type="email" name="userEmail" ng-model="email" required> <span ng-show="myForm.userEmail.$error.required">Required!</span> <span ng-show="myForm.userEmail.$error.email">Invalid email!</span> </form>

🔹 4. Filters

Used to format data in templates.

Filter Usage Example
currency Format as currency `{{ 123
uppercase Upper case `{{ name
date Format dates `{{ today
filter Filter arrays `ng-repeat="x in items

🔹 5. Services

Used to share logic/data across controllers.

Custom Service Example:

js
app.service('MathService', function() {
this.square = function(a) { return a * a; }; });

Inject in Controller:

js
app.controller('CalcController', function($scope, MathService) { $scope.result = MathService.square(4); });

🔹 6. Dependency Injection

AngularJS automatically injects dependencies into functions:

js
app.controller('MyController', function($scope, $http) { // $http is injected });

🔹 7. Routing (SPA)

With ngRoute, you can change views without reloading the page.

Add Script:

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

App Configuration:

js

var app = angular.module('myApp', ['ngRoute']); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.html" }) .when("/about", { templateUrl : "about.html" }); });

In HTML:

html
<div ng-view></div>

🔹 8. HTTP Requests

Using $http for AJAX calls:

js
app.controller('DataController', function($scope, $http) { $http.get("https://jsonplaceholder.typicode.com/posts") .then(function(response) { $scope.posts = response.data; }); });
html
<div ng-controller="DataController"> <ul> <li ng-repeat="post in posts">{{ post.title }}</li> </ul> </div>

🔹 9. Custom Directives

js
app.directive('myWelcome', function() { return { template: "<h3>Welcome to Custom Directive!</h3>" }; });
html
<my-welcome></my-welcome>

🔹 10. AngularJS vs jQuery

FeatureAngularJSjQuery
TypeFrameworkLibrary
PurposeBuild SPAsDOM Manipulation
Data BindingTwo-wayManual
MVC SupportYesNo

✅ Summary

ConceptDescription
ng-appBootstraps the AngularJS application
ng-modelBinds data between input and model
ng-controllerDefines logic and data for view
ng-repeatLoops through arrays
ng-clickBinds click events
$scopeObject used to share data between view and controller
$httpMakes AJAX requests
$routeProviderConfigures SPA routes
🔹 Basic AngularJS Application Example


angularjs-hello-world/ ├── index.html 👉 View (HTML Template) ├── app/ │ ├── app.module.js 👉 Main App Module (Bootstrap) │ ├── controllers/ │ │ └── hello.controller.js 👉 Controller (Business logic) │ └── models/ │ └── greeting.model.js 👉 Model (Optional - holds static/mock data)

📄 index.html (View)

html

<!DOCTYPE html> <html ng-app="helloApp"> <head> <meta charset="UTF-8"> <title>Hello AngularJS MVC</title> <!-- AngularJS CDN --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <!-- App Scripts --> <script src="app/app.module.js"></script> <script src="app/controllers/hello.controller.js"></script> <script src="app/models/greeting.model.js"></script> </head> <body> <div ng-controller="HelloController"> <h1>{{ greeting }}</h1> <input ng-model="greeting" placeholder="Change greeting"> </div> </body> </html>

📄 app/app.module.js (Main App Module)

javascript

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

📄 app/controllers/hello.controller.js (Controller)

javascript

app.controller('HelloController', function($scope, GreetingModel) { // Initialize greeting from model $scope.greeting = GreetingModel.getGreeting(); });

📄 app/models/greeting.model.js (Model)

javascript

app.factory('GreetingModel', function() { var greeting = "Hello AngularJS with MVC!"; return { getGreeting: function() { return greeting; }, setGreeting: function(newGreeting) { greeting = newGreeting; } }; });

💡 Explanation of MVC

ComponentFileRole
Modelgreeting.model.jsHolds and manages greeting data.
Viewindex.htmlHTML that binds to controller data.
Controllerhello.controller.jsConnects model to view via $scope.
Moduleapp.module.jsRegisters and bootstraps app and components.

🔹 Key AngularJS Concepts

ConceptExamplePurpose
ng-model<input ng-model="name">Binds input field to model.
ng-bind<span ng-bind="name"></span>Alternative to {{ name }} interpolation.
ng-repeat<li ng-repeat="item in items">{{ item }}</li>Loop through a list.
ng-click<button ng-click="sayHello()">Click Me</button>Binds a click handler.
ng-show / ng-hide<div ng-show="isVisible">Conditionally show/hide elements.


🔹 AngularJS vs Angular (2+)

FeatureAngularJS (1.x)Angular (2+)
LanguageJavaScriptTypeScript
ArchitectureMVCComponent-based
PerformanceSlowerFaster
Mobile SupportNoYes
SupportDeprecatedActively maintained

🔹 When to Use AngularJS Today

Good for:

  • Maintaining existing projects

  • Legacy applications in enterprises

  • Quick internal tools/prototypes

Not recommended for:

  • New production apps (use Angular 15+, React, or Vue.js)


Modern Angular (TypeScript-based) with a proper Angular project structure.

angular-hello-world/
├── src/
│   ├── app/
│   │   ├── greeting/
│   │   │   ├── greeting.component.ts       👉 Component (View + Controller)
│   │   │   ├── greeting.component.html     👉 View Template
│   │   │   ├── greeting.component.css      👉 Component-specific styles
│   │   │   └── greeting.service.ts         👉 Service (Model/logic)
│   │   └── app.module.ts                   👉 Root Module (Bootstrap)
│   └── main.ts                             👉 Entry Point
├── angular.json                            👉 Angular CLI config
├── package.json                            👉 Project dependencies

📦 Step-by-Step with Code

1️⃣ Create Project using Angular CLI

npm install -g @angular/cli
ng new angular-hello-world --routing=false --style=css
cd angular-hello-world

2️⃣ Generate Component and Service

ng generate component greeting
ng generate service greeting/greeting

3️⃣ app.module.ts – Root Module

// src/app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { GreetingComponent } from './greeting/greeting.component';

@NgModule({
  declarations: [AppComponent, GreetingComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

4️⃣ greeting.service.ts – Service (Model Equivalent)

// src/app/greeting/greeting.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class GreetingService {
  private greeting = "Hello Angular (v17) with MVC structure!";

  getGreeting(): string {
    return this.greeting;
  }

  setGreeting(newGreeting: string) {
    this.greeting = newGreeting;
  }
}

5️⃣ greeting.component.ts – Component (Controller + View Logic)

// src/app/greeting/greeting.component.ts

import { Component, OnInit } from '@angular/core';
import { GreetingService } from './greeting.service';

@Component({
  selector: 'app-greeting',
  templateUrl: './greeting.component.html',
  styleUrls: ['./greeting.component.css']
})
export class GreetingComponent implements OnInit {
  greeting: string = '';

  constructor(private greetingService: GreetingService) {}

  ngOnInit() {
    this.greeting = this.greetingService.getGreeting();
  }
}

6️⃣ greeting.component.html – View Template

<!-- src/app/greeting/greeting.component.html -->
<h1>{{ greeting }}</h1>
<input [(ngModel)]="greeting" placeholder="Change greeting">

7️⃣ app.component.html – App Root Template

<!-- src/app/app.component.html -->
<app-greeting></app-greeting>

✅ Result
When you run:

ng serve

You’ll see the below output:

Hello Angular (v17) with MVC structure!


🔁 Comparison: AngularJS vs Angular (Modern)

Feature AngularJS Angular (2+ / latest)
Language JavaScript TypeScript
Component Model Controller + Template Component (Class + Template + Metadata)
Module System Manual via script tags NgModules with @NgModule decorator
Dependency Injection Basic Hierarchical, powerful DI
Forms ng-model Template-driven or Reactive Forms
Routing ngRoute @angular/router
Build Tooling Manual or Grunt/Gulp Angular CLI + Webpack

✅ Summary of Modern Angular MVC Analogy

MVC Concept Angular
Model Service (e.g., GreetingService)
View HTML template (e.g., greeting.component.html)
Controller Component class (e.g., GreetingComponent)
Bootstrap Module (AppModule)


No comments:

Post a Comment