Understanding Features of AngularJS

29 dec. 2023
Beginner
2,31K Views
9 min read  

AngularJS is most powerful and adaptive JavaScript framework by the web developers and designers. In this article, you will learn the most important features of AngularJS and how they can help you to make your app awesome. For those aspiring to delve deeper into AngularJS and harness its capabilities to build exceptional applications, consider pursuing an Angular Certification.

AngularJS Features

  1. Modules

  2. Directives

  3. Templates

  4. Scope

  5. Expressions

  6. DataBinding

  7. MVC (Model, View & Controller)

  8. Validations

  9. Filters

  10. Services

  11. Routing

  12. Dependency Injection

  13. Testing

Modules

AngularJS modules divides your web application into small, reusable and functional components which can be integrated with other web applications. Each module is identified by a unique name and can be dependent on other modules.

Creating an AngularJS module

<script type="text/javascript">
angular.module('myApp',[]);
angular.module('myApp',['dependentModule1','dependentModule2']);
</script>

Using an AngularJS module into your app

You can bootstraps your app by using your angularJS module as given below:

<html ng-app="myApp">
<head>...</head>
<body>...</body>

Inside your angularjs module you can define following components:

  1. Controllers

  2. Services

  3. Factories

  4. Filters

  5. Directives etc.

Directives

AngularJS directives are used to extend the HTML vocabulary i.e they decorate html elements with new behaviors and help to manipulate html elements attributes in interesting way.

There are some built-in directives provided by angularjs like as ng-app, ng-controller, ng-repeat, ng-model etc. You can also create your own custom directive.

Using ng-repeat in Template

<!-- ng-repeat directive -->
<ul ng-controller='ProductController'>
<li ng-repeat='product in Products'>{{product.name}} = {{product.price}} </li> 
</ul>

<script>
function ProductController($scope){ 
$scope.Products = [{name: 'Soap', price: 120},
 {name: 'Shampoo', price: 100}, 
 {name: 'Hair Oil', price: 60}];
}
</script>

Templates

AngularJS templates are just plain old HTML that contains Angular-specific elements and attributes. AngularJS used these templates to show information from the model and controller.

Inside your angularjs templates you can define following angular elements and attributes:

  1. Directive

  2. Angular Markup ({{}})

  3. Filters

  4. Form controls

Creating Template

<html ng-app>
 <!-- Body tag with ngController directive -->
 <body ng-controller="MyController">
 <input ng-model="foo" value="bar">
 <!-- Button tag with ng-click directive, and string expression 'buttonText' is wrapped in "{{ }}" markup -->
 <button ng-click="changeFoo()">{{buttonText}}</button>
 <script src="angular.js">
 </body>
</html>

Expressions

Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. AngularJS expressions doesn't support control flow statements(conditionals, loops, or exceptions). These supports filters to format data before displaying it.

There are some valid angularjs expressions:

  1. {{ 1 + 2 }}

  2. {{ x + y }}

  3. {{ x == y }}

  4. {{ x = 2 }}

  5. {{ user.Id }}

  6. {{ items[index] }}

Data Binding

AngularJS data-binding is the most useful feature which save you from writing a considerable amount of boilerplate code. Now, developers are not responsible for manually manipulating the DOM elements and attributes to reflect model changes. AngularJS provides two-way data-binding to handle the synchronization of data between model and view.

The data-binding directives helps you to bind your model data to your app view. Use ng-model directive to create a two way data-binding between the input element and the target model.

<div ng-controller='HelloController'>
<input ng-model='name'/><!-- two way -->
 <p>Hello {{name}}</p> <!-- one way -->
</div>

<script>
function HelloController($scope)
{ 
 $scope.name = 'Dot Net Tricks' 
}
</script>

Scope

Scope is an object that refers to the application model. It acts as a context for evaluating expressions. Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your angularjs app.

Each angular app has a single scope ($rootscope) which mapped to the ng-app directive element.

Creating $scope in controllers

<script>
function ProductController($scope){ 
$scope.Products = [{name: 'Soap', price: 120},
 {name: 'Shampoo', price: 100}, 
 {name: 'Hair Oil', price: 60}];

}
</script>

Using Scope in Template

<!-- ng-repeat directive -->
<ul ng-controller='ProductController'>
<li ng-repeat='product in Products'>{{product.name}} = {{product.price}} 
</li> 
</ul>

MVC (Model, View & Controller)

AbgularJS is a MVC framework. It does not implement MVC in the traditional way, but rather something closer to MVVM Model-View-ViewModel).

The Model

Models are plain old JavaScript objects that represent data used by your app. Models are also used to represent your app's current state.

The ViewModel

A viewmodel is an object that provides specific data and methods to maintain specific views. Basically, it is a $scope object which lives within your angularjs app's controller. A viewmodel is associated with a HTML element with the ng-model & ng-bind directives.

Creating an AngularJS Controller with ViewModel

<script type="text/javascript">
//defining main controller
app.controller('mainController', ['$scope', function($scope) {

//defining book viewmodel
 $scope.book = 
 {
 id: 1,
 name: 'AngularJS Interview Questions and Answers',
 author: 'Shailendra Chauhan',
 };
}]);
</script>

The Controller

The controller define the actual behavior of your app. It contains business logic for the view and connects the right models to the right views. A controller is associated with a HTML element with the ng-controller directive.

The View

The view is responsible for presenting your models data to end user. Typically it is the HTML markup which exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.

Using an AngularJS controller into your app

<!-- The View -->
<div ng-controller="mainController">
 Id: <span ng-bind="book.id"></span>
 <br/>
 Name:<input type="text" ng-model="book.name" />
 <br/>
 Author: <input type="text" ng-model="book.author" />
</div>

Validation

AngularJS form validation enables you to develop a modern HTML5 form that is interactive and responsive. AngularJS provides you built-in validation directives to achieve form validation and they are based on the HTML5 form validators. You can also create your own custom validators.

Here is a list of angularjs directive which can be apply on a input field to validate it's value.

<inputtype="text"
 ng-model="{ string }"
 [name="{ string }"[
 [ng-required="{ boolean }"]
 [ng-minlength="{ number }"]
 [ng-maxlength="{ number }"]
 [ng-pattern="{ string }"]
 [ng-change="{ string }"]>
</input>

Filter

Filters are used to format data before displaying it to the user. They can be used in view templates, controllers, services and directives. There are some built-in filters provided by angularjs like as Currency, Date, Number, OrderBy, Lowercase, Uppercase etc. You can also create your own filters.

Filter Syntax

{{ expression | filter}}

Filter Example

<script type="text/javascript">
{{ 14 | currency }} //returns $14.00
</script>

Services

Services are reusable singleton objects that are used to organize and share code across your app. They can be injected into controllers, filters, directives.

$http Service

<script>
$http.get('/products')
.success(function(data) { 
 $scope.products = data; 
 }); 
});
</script>

AngularJS offers several built-in services (like $http, $provide, $resource,$window,$parse) which always start with $ sign. You can also create your own services

Routing

AngularJS Routing helps you to divide your app into multiple views and bind different views to Controllers. The magic of Routing is taken care by a angularjs service $routeProvider. $routeProvider service provides method .when() and .otherwise() to define the routes for your app. Routing has dependency on ngRoute module.

<script type="text/javascript">
var myApp = angular.module('myApp', ['ngRoute']);
 
myApp.config(['$routeProvider',
 function($routeProvider) {
 $routeProvider.
 when('/products', { //route
 templateUrl: 'views/products.html', 
 controller: 'productController'
 }).
 when('/product/:productId', { //route with parameter
 templateUrl: 'views/product.html',
 controller: 'productController'
 }).
 otherwise({ //default route
 redirectTo: '/index' 
 });
 }]);
</script>

Dependency Injection

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies. AngularJS comes with a built-in dependency injection mechanism. You can divide your angularjs app into multiple different types of components which angularjs can inject into each other.

Dependency Annotation

There are following three ways of injecting dependencies into your code:

  1. Implicitly from the function parameter names

    <script type="text/javascript">
    function MyController($scope, greeter) {
     // ...
    }
    </script>
    
  2. Using the $inject property annotation

    <script type="text/javascript">
    var MyController = function(renamed$scope, renamedGreeter) {
     ...
    }
    
    MyController['$inject'] = ['$scope', 'greeter'];
    </script>
    
  3. Using the inline array annotation

    <script type="text/javascript">
    someModule.factory('greeter', ['$window', function(renamed$window) {
     // ...
    }]);
    </script>
    

Testing

AngularJS is designed to be testable so that you can test your AngularJS applications as easy as possible. It also comes with an end-to-end and unit test runner setup.

What do you think?

I hope you will enjoy the AngularJS features while developing your app with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome. For those interested in gaining a deeper understanding of AngularJS features and leveraging them effectively in app development, consider exploring an Angular Certification course.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Learn to Crack Your Technical Interview

Accept cookies & close this