Learn AngularJS From Beginning - Part One

Actually, In this article, we will discuss the basics of Angular JS. We will also discuss how to write down a very basic program in AngularJS.

Introduction

In 1990, Tim Berners Lee introduced a new markup language named HTML (Hyper Text Markup Language). The main objective of developing HTML was to share information between different computers in a common readable format. In the beginning, HTML is used to share static documents with hyperlinks and allow navigation between them. After that, in 1993, with the introduction of CGI (Common Gateway Interface), it was possible to display dynamic content generated by server-side applications. At that time, Perl, followed by Java, PHP, etc. was used for this purpose. However, interaction with complex applications through the browser was not enjoyable to work, and sometimes, this task became very hard to execute. But technology always kept moving forward. So, at the same time, new versions of JavaScript, CSS, and HTML were growing in popularity and also transforming the future of the web at a high level. AngularJS is a part of this new generation of libraries and frameworks that came to support the development of more productive, flexible, and testable environments for web applications.

AngularJS was actually introduced in 2009 by Misko Hevery and Adam Abrons as an open-source, client-side javascript-based framework that supports a high-productivity web development experience. It was built on the belief that declarative programming is the best choice to construct the user interface, while imperative programming is much better and preferred to implement an application's business logic. To achieve this, AngularJS used traditional HTML by extending its current vocabulary, making the lives of developers easier. In 2010, Miško Hevery was working at Google on a project called Feedback. For the large size of code in that project, Misko rewrote the project using his own client-side framework and reduced the code size by nearly 10 times. Nowadays, the framework is used by more than 100 projects just at Google. The name of the framework was given by Adam Abrons, and it was inspired by the angle brackets of the HTML elements.

JavaScript Client-Side Framework

JavaScript-based client-side applications always run on the user’s device or PC, which shifts the workload to the user’s hardware and away from the server. At the same time, like other server-side-based MVC frameworks like Struts, Spring MVC, or ASP.NET  it cannot be switched the entire load from the server machine to the client machine. Javascript-based client-side framework provides many significant advantages such as simplicity, rapid development, testability, and also the ability to package the entire application and deploy it on all mobile devices and the web with related ease.

AngularJS makes the process even more faster and easier. Angular JS helps us to develop the frontend UI in a short time with proper support for unit testing for the client-side code. Models and views in AngularJS are much simpler than what you find in most Javascript client-side frameworks. Controllers, often missing in other javascript frameworks, are likely the most functional components in Angular JS. Once the AngularJS application is launched, the model, view, controller, and all HTML documents are loaded on the user’s device and completely run on the user’s hardware. As per the diagram below, we can see that calls are made to the backend REST services, where all business logic and business processes are loaded. The backend REST service can be located on any server, whether it is a private web server or a cloud server.

REST services

ng-app

Now, we can write the same program by declaring the angular module in just the line below. Now, the definition of an angular module is as below.

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

Write a Hello World in Angular JS.

To do this, we need to create one html file and another js file.

Code of App.js

var testApp = angular.module('TestApp', []);

Code of HelloWorld.html

<!DOCTYPE html>
<html ng-app="TestApp">
<head>
    <title>AngularJS</title>
    <script src="angular.js"></script>
    <script src="app.js"></script>
    <script src="HelloWorld.js"></script>
</head>
<body>
    <div ng-controller="HelloController">
        <p>{{greeting.text}}, World</p>
    </div>
</body>
</html>

Code of Helloworld.js

testApp.controller('HelloController', function($scope) {
    $scope.greeting = { text: 'Hello' };
});

Basically, the angular module acts as a main entry point for the angular applications. The pair bracket basically indicates the dependency injection concepts. This is one of the main advantages of AngularJS. Dependency injection (DI) is a design pattern where dependencies are defined in an application as part of the configuration. It helps us to avoid creating manual application dependencies. AngularJS uses dependency injection to load module dependencies when an application first starts. Actually, dependency injection is not a new concept. It was around a 10-year-old concept, and although it was consistently used in various frameworks.

Angular JS Models ($scope)

Many JavaScript client-side frameworks also require you to create a JavaScript model class. But it has not happened with AngularJS. AngularJS has a $scope object that is used to store the application models. Scopes are attached to the DOM. The way to access the model is by using data properties to the $scope objects. The AngularJS $scope helps considerably simplify Javascript Applications. In AngularJS, $scope is used to gain access to the model related to a particular controller. $rootscope is a parent scope that can be used to save and access model properties that span multiple controllers. However, the use of $rootscope is highly discouraged in most designs. There is only one $rootscope in an application. $scope is a child scope of $rootscope. A properly designed AngularJS application will have little or ideally no use of $rootscope to store model properties. Model properties can be added to the scope objects, and once added, they are available inside the view html templates.

Angular JS Controllers (ng-controllers)

In AngularJS, controllers act as a connection or bridge between views (i.e. HTML) and models (i.e. $scope). The controller is the area where we place all business logic that is specific to a particular view. When business logic is placed inside an application used by multiple controllers, it should be placed in AngularJS non-REST Services instead. Those services can be injected into any controller that needs to access that business logic with the help of dependency injection.

AngularJS

AngularJS controllers are the center of AngularJS applications and are probably the most important component to understand. AngularJS controllers have two main duties in an application. First, controllers should be used to initialize the model scope properties. When a controller is created and attached to the DOM, a child scope is created. The child scope holds a model used specifically for the controller to which it is attached. We can access the child scope by using $scope objects.

The second primary use of controllers is adding behavior of the $scope objects. We add behavior by adding a method to the scope objects.

Presentation logic should not be placed inside the controllers but instead should be placed in the view. AngularJS has many features for DOM manipulation that help you avoid placing presentation logic in the controllers. The controller is also not the place where you should format data. AngularJS has features specially designed for formatting data, and that’s where data formatting should take place.

I will demonstrate the concept of controller objects in the below example.

FirstProg.html

<!DOCTYPE html>
<html ng-app="TestApp">
<head>
    <title>Angular JS -- First Prog</title>
    <script src="angular.js"></script>
    <script src="app.js"></script>
    <script src="FirstProg.js"></script>
</head>
<body>
    <div ng-controller="FirstProgController">
        <h1>Enter Your Name :</h1>
        <input type="text" width="200px" ng-model="name" />
        <h2>Your Name: {{name}}</h2>
    </div>
</body>
</html>

FirstProg.Js

testApp.controller('FirstProgController', function($scope) {
    $scope.name = '';
});

Nested Controller

In AngularJS, we can use the controllers in a nested concept. Since we need to attach the controller with the DOM, so we can attach multiple controllers at different levels of the DOM hierarchy. Since the controller directive creates a new child scope, so we get a hierarchy of scopes that inherit from each other. The $scope that each Controller receives will have access to properties and methods defined by Controllers higher up the hierarchy. In the example below, we create 3 nested controller directives, which results in creating four different scopes for the view.

  1. The root scope
  2. The first controller scope, which contains message and userName properties
  3. The SecondController scope, which inherits the message property but overrides (hides) the userName property from the previous
  4. The ThirdController scope overrides (hides) both the message property defined in FirstController and the userName property defined in SecondController.

In the example below, I will demonstrate this concept of a nested controller.

Nestted.html

<!DOCTYPE html>
<html ng-app="TestApp">
<head>
    <title>Angular JS -- First Prog</title>
    <script src="angular.js"></script>
    <script src="app.js"></script>
    <script src="nested.js"></script>
</head>
<body>
    <div ng-controller="FirstController">
        <p>Welcome {{username}}, {{message}}!</p>
        <hr />
        <div ng-controller="SecondController">
            <p>Welcome {{username}}, {{message}}!</p>
            <hr />
            <div ng-controller="ThirdController">
                <p>Welcome {{username}}, {{message}}!</p>
            </div>
        </div>
    </div>
</body>
</html>

nested.js

testApp.controller('FirstController', function($scope) {
    $scope.username = 'Rabin';
    $scope.message = 'You logged in after 7 days.';
});

testApp.controller('SecondController', function($scope) {
    $scope.username = 'Scott';
});

testApp.controller('ThirdController', function($scope) {
    $scope.username = 'Thomash';
    $scope.message = 'This is your first time login..';
});

ControllerAs Syntax

From AngularJS 1.1.5, angularjs introduced support for the “Controller As” syntax. Using a controller makes it obvious which controller you 1are accessing in the template when multiple controllers apply to an element.

ControllerAs.html

<!DOCTYPE html>
<html ng-app="TestApp">
<head>
    <title>Angular JS -- First Prog</title>
    <script src="angular.js"></script>
    <script src="app.js"></script>
    <script src="ControllerAs.js"></script>
</head>
<body>
    <div ng-controller="TestController as a">
        <h2>Hello {{a.username}}</h2>
        <h1>Enter Your Name :</h1>
        <input type="text" width="200px" ng-model="a.name" />
        <h2>Your Name: {{a.name}}</h2>
    </div>
</body>
</html>

ControllerAs.js

testApp.controller('TestController', function() {
    var self = this;
    self.name = '';
    self.username = 'Sujit';
});

Read more articles on AngularJS.