Angular.js (1.X) Fundamentals

What is Angular.js ?

  • A client side javascript framework for adding interactivity to HTML.
  • It lets you use good old HTML and lets you extend HTML’s syntax to express your application’s components clearly.
  • It automatically synchronizes data from your UI (view) with your JavaScript objects (model) through 2-way data binding.
  • To help you structure your application better and make it easy to test, AngularJS teaches the browser how to do dependency injection and inversion of control.

Quick Introduction to Angular.js:


Demo

Directives:

A directive is a marker on a html tag that tell Angular to run or reference some javascript code.

Example: ng-controller is directive that tells angular which controller to use for the div.

Source
Screen Shot 2016-03-10 at 11.11.51 PM.png

Modules:

Is used for writing pieces of application. Module is a container for the different parts of your app — controllers, directives , filters and services.

Example: Are instantiated with angular.module.  myApp is the name of module and second parameter is an dependency.

Source
Screen Shot 2016-03-10 at 10.54.16 PM.png

Expressions:

Allow you to insert dynamic values to your html.  Often used by  {{}} syntax.

Example: {{counter}} will display the value which is set in the MyController.

Screen Shot 2016-03-10 at 10.55.46 PM.png

Controllers :

Where we define app behavior by defining functions and values. Controller are used to set up initial state of $scope object. Add behavior to $scope object.

Example: controller are instantiated with app.controller. MyController is name of controller. Second parameter is a callback function to initialize the state of this controller.

Screen Shot 2016-03-10 at 10.57.05 PM.png

Filters:

Can be used to validate or format the data in UI.

Screen Shot 2016-03-10 at 10.58.26 PM.png

Services:

Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

Angular services are:

  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
Source
Screen Shot 2016-03-10 at 11.00.55 PM.png

Two way data Binding:

Is the automatic synchronization of data between the model and view components. The view reflection of model. If model changes view reflects the change and vice versa.

Source
Screen Shot 2016-03-10 at 11.04.55 PM.png

Single Page Apps (SPA) :

Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app. ngRoute module provides routing and deep linking services and directives for angular apps. $routeProvider is used for configuring routes.

Source:
Screen Shot 2016-03-10 at 11.18.43 PM

Some Interviews question on Angular.js:

Is it a good or bad practice to use AngularJS together with jQuery?

It is bad practice to mix JQuery and Angular.js. DOM manipulation should be done in Angular.js via directive.

What is the difference between one-way binding and two-way binding?

One way binding implies that the scope variable in the html will be set to the first value when its model is updated.
Two way binding implies that the scope variable will change it’s value every time its model is assigned to a different value.

What is the role of services in AngularJS and name any services made available by default?

– AngularJS Services are objects that provide separation of concerns to an AngularJS app.
– AngularJS Services can be created using a factory method or a service method.
– Services are singleton components. All components of the application (into which the service is injected) will work with single instance of the service.
– An AngularJS service allows developing of business logic without depending on the View logic which will work with it.

-Services are the best may to evolve reusable API within and AngularJS app

Few of the inbuilt services in AngularJS are:
– the $http service: The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP
– the $log service: Simple service for logging. Default implementation safely writes the message into the browser’s console
– the $anchorScroll: it scrolls to the element related to the specified hash or (if omitted) to the current value of $location.hash()

Explain what is a $scope in AngularJS?

Scope is an object that refers to the application model. It is an execution context for expressions. Scopes can watch expressions and propagate events. Scopes are objects that refer to the model. They act as glue between controller and view.

How would you implement application-wide exception handling in your Angular app?

Angular has a built-in error handler service called $exceptionHandler which can easily be overridden as seen below:

myApp.factory('$exceptionHandler', function($log, ErrorService) {
    return function(exception, cause) {
        
        if (console) {
            $log.error(exception);
            $log.error(cause);
        }

        ErrorService.send(exception, cause);
    };
});

List at least three ways to communicate between modules of your application using core AngularJS functionality.

Common ways to communicate between modules of your application using core AngularJS functionality include:

  • Using services
  • Using events
  • By assigning models on $rootScope
  • Directly between controllers, using $parent, $$childHead, $$nextSibling, etc.
  • Directly between controllers, using ControllerAs, or other forms of inheritance

What is $rootScope and how does it relate to $scope?

$rootScope is the parent object of all $scope that Angular objects created in a web page.

List a few ways to improve performance in an AngularJS app?

The two officially recommended methods for production are disabling debug data and enabling strict DI mode.

The first one can be enabled through the $compileProvider:

myApp.config(function ($compileProvider) {
  $compileProvider.debugInfoEnabled(false);
});

That tweak disables appending scope to elements, making scopes inaccessible from the console. The second one can be set as a directive:

<html ng-app=“myApp” ng-strict-di>

The performance gain lies in the fact that the injected modules are annotated explicitly, hence they don’t need to be discovered dynamically.

You don’t need to annotate yourself, just use some automated build tool and library for that.

Two other popular ways are:

  • Using one-time binding where possible. Those bindings are set, e.g. in “{{ ::someModel }}” interpolations by prefixing the model with two colons. In such a case, no watch is set and the model is ignored during digest.
  • Making $httpProvider use applyAsync:
myApp.config(function ($httpProvider) {
  $httpProvider.useApplyAsync(true);
});

… which executes nearby digest calls just once, using a zero timeout.

How does the digest phase work?

In a nutshell, on every digest cycle all scope models are compared against their previous values. That is dirty checking. If change is detected, the watches set on that model are fired. Then another digest cycle executes, and so on until all models are stable.

It is probably important to mention that there is no “.$digest()” polling. That means that every time it is being called deliberately. As long as core directives are used, we don’t need to worry, but when external code changes models the digest cycle needs to be called manually. Usually to do that, “.$apply()” or similar is used, and not “.$digest()” directly.

Sample Applications

  • Sample TODO app: Sample todo app built on Angular.js. It uses also basic concepts of angular : Scope, Model, Controller and Directives. Click on demo link :  Demo
  •  Another book search app built on Angular.Click here to view this project. This app is  build on angular and node.js. It uses all core angular concepts such as Directives, ng-  controller and ng-model.
  • Sample application to play with angular services. Click on demo link : Demo
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s