AngularJS: A Detailed Guide for Beginners

If you’ve not got your hands on AngularJS yet, you’re missing awesome features that can really make the most of HTML for web apps. Unlike Backbone.js and Ember.js, AngularJS is a next generation JavaScript framework where each component works with every other component in an interconnected way to make your web applications stand out.

This article is designed to give a comprehensive knowledge of AngularJS, a structural framework for dynamic web applications, without reading a lot of unnecessary stuff. You will learn what AngularJS is, what its most compelling features are and how to get started with it.

AngularJS Introduction

AngularJS is an open-source web application framework designed with the aim of making development and testing tasks easier for web developers. It is a fully extensible client-side MVC/MVVM framework that runs with no library dependencies and also works well with other libraries. Being pure JavaScript, Angular JS is perfect for creating one-page web apps that only require client-side languages such as HTML, CSS and JavaScript. The best thing is that you’re allowed to modify or replace its any feature to fit your unique development workflow and project requirements.

Developed in 2009 by highly talented Google engineers Miško Hevery and Adam Abrons, AngularJS is a “superheroic JavaScript MVW framework for dynamic web apps” which enables you use HTML as your template language and allows you to extend HTML vocabulary, so you could express your application’s components in a clear, concise manner. Helping you structure and test your Javascript code better, AngularJS teaches the browser how to be an ideal partner with any server technology by making use of dependency injection and inversion of control. The main goal of this structural framework is to augment web apps with MVC (Model–View–Controller) capability.

Notable Features

Unlike many other frameworks, AngularJS is an advanced framework that has some outstanding features which are equally helpful for not only developers, but designers. Below are some amazing features of AngularJS, which enable developers create next generation web applications.

Directives

Directives is the most unique, dominant and powerful feature available only in AngularJS. They allows developers to create custom and reusable HTML components, which can be used to hide complex DOM structure and “decorate” certain elements with behavior. They enable you extend your HTML by letting you invent new HTML syntax, and instruct AngularJS to incorporate its functionality into the page. Prefaced with ng-, all of the Directives take place in HTML attributes and work as standalone elements.

Best Designed WordPress and Bootstrap Themes

Designmodo Shop

Following are some of the most used Directives:

  • ng-app: This directive declares an element as application’s root element and is typically placed in the <body> or <html> tags. <html ng-app> is all needed to declare a page as an Angular application.
  • ng-bind: It replaces the text content of an HTML component with the value of an expression, and updates the text content with the changes made in the value of that expression.
  • ng-controller: It is used to define a JavaScript controller class to evaluate HTML expressions.
  • ng-model: The ng-model attribute is similar to ng-bind, except it is responsible for two-way data binding between the scope defined in the model and the view.
  • ng-repeat: It instantiates a template once per item, to which the loop variable is set, from a collection.
  • ng-class: This directive allows class attributes to load dynamically.
  • ngIf: This basic if statement directive is used to re-insert or eliminate an element from the DOM, depending on whether the condition is true or false.
  • ng-hide and ng-show: According to Boolean expression’s value, these attributes conditionally display or hide an element.

Below is an easy example of a directive, which first listens for an event and then makes required changes in its $scope, accordingly.

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

You can make use of this custom directive as following:

<my-component ng-model="message"></my-component>

Two-Way Data Binding

Data-binding is the second most powerful and compelling feature of AngularJS. It eliminates a considerable amount of unnecessary code you’ve to write by releasing the server backend from various templated responsibilities. Generally, 80 percent code base of a typical web application is dedicated to manipulating, traversing, and listening to DOM events. Angular’s data binding hides this code, letting you focus on other vital aspects of your web application.

Generally, in most templating systems, data binding occurs only in one direction. The classical template system merges template and model together into a view. After this one-time merge, changes made in the model components and other sections of the view are not reflected in the view automatically. Worse, any alterations made by the user to the view are also not reflected in the model. This means, in order to constantly sync the model with the view and the view with the model, developers need to manually manipulate the elements and attributes of DOM.

When a user makes any change to the view, this process becomes even more arduous and complicated. Because then, the developer is responsible for interpreting the user interactions, merging them into the model, and updating the model whenever any changes occur in the view.

AngularJS

On the other hand, the AngularJS template works in a different and better way. Saving the developers from putting data into the view manually, it automatically synchronizes the data between the model and the view, and vice versa.

Angularjs guide

Here is a simple example where binding of an input value to an <h1> tag is demonstrated.

<!doctype html>
<html ng-app>
  <head>
    <script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script>
  </head>
  <body>
    <div>
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <hr>
      <h1>Hello, {{yourName}}!</h1>
    </div>
  </body>
</html>

Dependency Injection

AngularJS comes with a built-in injector subsystem that is in charge of creating components, looking up dependencies, and passing them to other components when needed. The dependency injection in AngularJS enables developers to declare how the web app is wired. By taking advantage of dependency injection, AngularJS carries traditional services – like view-dependent controllers – from server side to web applications on client side. Thus, much of the burden on server backend is reduced, resulting in a much lighter and faster web application.

In order to access core AngularJS services, you just need to add that service as a parameter. AngularJS will automatically detect that you’ve requested that service, and will provide you an instance.

function EditCtrl($scope, $location, $routeParams) {
     // Write something here...
}

Moreover, you can also define your own custom services and make them easy to get to injection.

    module('MyServiceModule', []).
    factory('notify', ['$window', function (win) {
    return function (msg) {
        win.alert(msg);
    };
}]);
function myController(scope, notifyService) {
    scope.callNotify = function (msg) {
        notifyService(msg);
    };
}
myController.$inject = ['$scope', 'notify'];

Templates

In AngularJS, templates are written with HTML, containing Angular-specific components and attributes. AngularJS merges template and information (from the model and controller) together to render the dynamic view for a user in the browser.

Below are the types of AngularJS attributes and elements that are used:

  • Directive: This element or attribute augments an existing DOM component or renders a reusable DOM element.
  • Markup: It binds expressions to elements, making use of the double curly brace notation {{ }}.
  • Form Controls: It validates user input.
  • Filter: This element formats data for display.

Here is an example, showing a template with directives and double curly-brace notations:

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

In a simple web application, the template has Angular directives, HTML and CSS in only one HTML file (such as index.html). While in a complex application, you can show multiple views in the main page by making use of “partials” that are segments of template, which resides in different HTML files.

Testing

Given the fact that JavaScript is a dynamically typed language which comes without any help from the compiler. For this reason, the AngularJS team has designed AngularJS to be testing ready since they feel very strongly that any JavaScript code should go through a strong set of different tests. AngularJS ships with many built in incredible testing features, which make it as easy as possible for developers to test their web applications.

For end-to-end testing, AngularJS uses “Protractor,” an end to end test runner which removes test flakiness by understanding how Angular works internally and emulates user interactions with your app. With AngularJS, you can also perform Unit testing for testing individual units of your code. Best of all, the Angular team has built an extension for the Google Chrome browser, called AngularJS Batarang, using which you can easily detect performance bottlenecks and debug your applications within browser.

Getting Started With AngularJS

Building web apps with AngularJS is as easy as 1-2-3. To get started, you just need to add a few attributes to your HTML. Follow the steps given below to get your Angular app up in just 5 minutes.

Add the ng-app directive to your <html> tag. It’ll tell Angular where it should get activated, declaring the page as Angular application.

<html lang="en" ng-app>

Now put the Angular <script> tag in your page, just before the ending of <head> tag.

<script src="lib/angular/angular.js"></script>

Finally, add regular HTML. AngularJS directives are accessed through HTML attributes, while expressions are evaluated with {} notation.

<body ng-controller=”VisitorsListCtrl”>
<h1>Today's Visitors</h1>
<ul>
<li ng-repeat=”visitors in visitors”>
{{visitor.name}}
</li>
</ul>
</body>
</html>

In the above code, the ng-controller directive defines the JavaScript class for a given action, while the directive ng-repeat (which is an Angular repeater object) instructs Angular for creating list elements as long as visitors are available to display.

Let me know what you think about AngularJS in the comments below:

  • Have I missed any of AngularJS features?
  • Have you created any great app using AngularJS?
  • What you think about the future of AngularJS?

Ajeet is an experienced web developer at CreativeWebLogix - Get Your Existing Site to Responsive. His current love interest is AngularJS, and he is also passionate about writing on WordPress, HTML5, CSS3, and Responsive. Don't forget to follow @CWL_WEBDESIGN to get latest updates via Twitter.

Newsletter

6 Comments
  1. Rahul Guha Jul 14, 6:10 pm

    Great read. Other aspects of angular I would mention are:
    1. Flexible routing
    2. Obseever pattern support out of the box
    3. Service for state, data and common code organization.
    4. Default support for async and promise.

    I built end to end ecommerce platform and multiple business app in angular which are released as web app, mobile web and native mobile app through phone gap.

    I think angular is a great framework. Once u r familiar with this you dont want to go anywhere unless really forced. In future I expect to see directives to merge with polymar web components and see more enhancement on touch features.

    cheers … Rahul

    Reply
    +10
  2. neil Jul 15, 11:28 pm

    I like the explanation, but don’t understand your example code, you’re using VisitorsListCtrl but not explaining what you’re doing. It also doesn’t do anything. I feel like I’m missing something.

    Reply
    +7
    • Ajeet Yadav Jul 21, 10:11 am

      Hello Neil,

      ‘VisitorsListCtrl’ is the name of my imaginary JavaScript class, which tells Angular what code to run.

      To grab something from Angular, you’ve to fetch your data with a JavaScript file containing a function whose name corresponds to the controller you’ve outlined in your HTML. Here is the example:

      function VisitorsListCtrl($scope) {
      $scope.visitors = [
      { “name”: “Alex” },
      { “name”: “Jeff” },
      { “name”: “Eddie” },
      { “name”: “Bruno” },
      { “name”: “Steve” }
      ];
      }

      Reply
      +3
  3. Stephen Jul 29, 1:48 pm

    How can I use Startup Framework with angular?

    Reply
    +1
  4. Diwakar Nov 25, 1:21 pm

    Hi Ajeet,

    i am going to develop a website using angularJS,html5 and css3 and i have backend webservices which are already exposed.Can u pls tell me what is the best approach of developing web application.

    I mean initial web application directory structure.

    Thanks in advance

    Regard’s,
    Diwakar.

    Reply
    0

Leave a Reply

*
* Minimum length: 20 characters