Angular Js Dom Tutorial

Angular Js Dom Tutorial

Last updated on 10th Oct 2020, Blog, Tutorials

About author

Sanjay ((Senior Architect in Angular JS, Infosys ) )

He is Possessing 10+ Years Of Experience in AngularJS. Her Passion lies in Developing Entrepreneurs & Activities. Also, Rendered her intelligence to the Enthusiastic JOB Seekers.

(5.0) | 12547 Ratings 2212

In this Angular HTML DOM Tutorial, we are going to explore why DOM is used and different types of directives used in DOM: ng-disabled, ng-hide, ng-click, and ng-show with their syntax.

What is DOM in AngularJS?

The logical structure of documents and documents are accessed and manipulated are defined using DOM elements. It defines events, methods, properties for all HTML elements as objects. DOM in AngularJS acts as an API (programming interface) for javascript.

Whenever a web page is loaded, the browser creates a Document Model Object (DOM) of that page.

Subscribe For Free Demo

Error: Contact form not found.

Why DOM is used?

A programmer can use DOM in AngularJS for the following purposes:

  • Documents are built using DOM elements.
  • A Programmer can navigate documents structure with DOM elements.
  • A programmer can add elements and content with DOM elements.
  • Programmer can modify elements and content with DOM elements.

Directives for AngularJS HTML DOM

We can use various directives to bind the application data to the attributes of DOM elements. Some of them are:

  • ng-disabled
  • ng-hide
  • ng-click
  • Ng-show

ng-disabled Directive

Add ng-disabled attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.

  • <input type = “checkbox” ng-model = “enableDisableButton”>Disable Button
  • <button ng-disabled = “enableDisableButton”>Click Me!</button>

ng-show Directive

Add ng-show attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.

  • <input type = “checkbox” ng-model = “showHide1″>Show Button
  • <button ng-show = “showHide1″>Click Me!</button>

ng-hide Directive

Add ng-hide attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.

  • <input type = “checkbox” ng-model = “showHide2″>Hide Button
  • <button ng-hide = “showHide2″>Click Me!</button>

ng-click Directive

Add ng-click attribute to an HTML button and update a model. Bind the model to HTML and see the variation.

  • <p>Total click: {{ clickCounter }}</p>
  • <button ng-click = “clickCounter = clickCounter + 1″>Click Me!</button>

AngularJS Tutorial

AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.

Why to Learn AngularJS?

AngularJS is an open-source web application framework. It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.2.21.

  • AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
  • AngularJS provides developers an options to write client side applications using JavaScript in a clean Model View Controller (MVC) way.
  • Applications written in AngularJS are cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.

Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain web applications.

Hello World using AngularJS.

Just to give you a little excitement about AngularJS, I’m going to give you a small conventional AngularJS Hello World program, You can try it using Demo link.

Applications of AngularJS

The general features of AngularJS are as follows −

  • AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
  • AngularJS provides developers an options to write client side applications using JavaScript in a clean Model View Controller (MVC) way.
  • Applications written in AngularJS are cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.

Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain web applications.

Audience

This tutorial is designed for software professionals who want to learn the basics of AngularJS and its programming concepts in simple and easy steps. It describes the components of AngularJS with suitable examples.

Prerequisites

You should have a basic understanding of JavaScript and any text editor. As we are going to develop web-based applications using AngularJS, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX, etc

AngularJS Directives

We used directives in our first AngularJS application section. Here, we will learn directives in detail.

Directives are markers on a DOM element that tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element and its children. In short, it extends the HTML.

Most of the directives in AngularJS are starting with ng- where ng stands for Angular. AngularJS includes various built-in directives. In addition to this, you can create custom directives for your application.

The following table lists the important built-in AngularJS directives.

DirectiveDescription
ng-appAuto bootstrap AngularJS application.
ng-initInitializes AngularJS variables
ng-modelBinds HTML control’s value to a property on the $scope object.
ng-controllerAttaches the controller of MVC to the view.
ng-bindReplaces the value of HTML control with the value of specified AngularJS expression.
ng-repeatRepeats HTML template once per each item in the specified collection.
ng-showDisplay HTML element based on the value of the specified expression.
ng-readonlyMakes HTML element read-only based on the value of the specified expression.
ng-disabledSets the disable attribute on the HTML element if specified expression evaluates to true.
ng-ifRemoves or recreates HTML element based on an expression.
ng-clickSpecifies custom behavior when an element is clicked.
Course Curriculum

Learn From AngularJS Training to Build Your Skills & Knowledge

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

ng-app

The ng-app directive initializes AngularJS and makes the specified element a root element of the application. Visit ng-app section for more information.

ng-init

The ng-init directive can be used to initialize variables in AngularJS application.

The following example demonstrates ng-init directive that initializes variable of string, number, array, and object.

ng-model

The ng-model directive is used for two-way data binding in AngularJS. It binds <input>, <select> or <textarea> elements to a specified property on the $scope object. So, the value of the element will be the value of a property and vica-versa.

The property set via ng-model can be accessed in a controller using $scope object. We will look at it in the next section.

Note : Variables initialized in ng-init are different from the properties defined using ng-model directive. The variables initialized in ng-init are not attached to $scope object whereas ng-model properties are attached to $scope object.

ng-bind

The ng-bind directive binds the model property declared via $scope or ng-model directive or the result of an expression to the HTML element. It also updates an element if the value of an expression changes.

ng-repeat

The ng-repeat directive repeats HTML once per each item in the specified array collection.

ng-repeat is used with students array. It creates <li> element for each item in the students array. Using the same way it repeats the <div> element.

ng-if

The ng-if directive creates or removes an HTML element based on the Boolean value returned from the specified expression. If an expression returns true then it recreates an element otherwise removes an element from the HTML document.

ng-readonly

The ng-readonly directive makes an HTML element read-only, based on the Boolean value returned from the specified expression. If an expression returns true then the element will become read-only, otherwise not.

ng-disabled

The ng-disabled directive disables an HTML element, based on the Boolean value returned from the specified expression. If an expression returns true the element will be disabled, otherwise not.

Directive Syntax

AngularJS directives can be applied to DOM elements in many ways. It is not mandatory to use ng- syntax only.

Directive can start with x- or data-, for example ng-model directive can be written as data-ng-model or x-ng-model.

Also, the – in the directive can be replaced with : or _ or both. For example, ng-model can be written as ng_model or ng:model. It can also be a mix with data- or x-.

AngularJS for Beginners – Essential Tips and Tricks

At the onset, you may find AngularJS easy to start but a large part of the code hides behind the abstraction layer that even the experienced developers wouldn’t like to explore due to its sheer size and complexity. Hence, these tips would also focus on making you familiar with such concepts.

  • Optimized code structure.
  • Understand Scope In AngularJS.
  • Restrain From Doing DOM Manipulation.
  • Use Service To Share Data Between Controllers.
  • Don’t Use Controllers For Presentation Logic.
  • Use Track By For Quickly Displaying List Items.
  • Adapt ControllerAs Approach.
  • Integrate Less To Produce CSS.
  • Use Built-In Validations In AngularJS.
  • Avoid Filters With Large Arrays.
  • How To Detect If Property Changes.
  • How To Detect If An Item Changes In A List.
  • Slow Down The Watchers From Being Called.
  • Select An Element By ID Or Class.
  • Use Multiple Controllers In Separate Modules.

1. Optimized code structure.

As someone rightfully said, “Without a solid foundation, you’ll have trouble creating anything of value.“. And as is the case with many of us who begin writing code to finish but don’t focus on the maintainability. Hence, you must plan for everything starting from the folder structure for your code. Here is a sample code structure for an AngularJS project that you may follow.

  • Create an “app” folder – the root of your project.
  • Place all your shared data in the “app/common” folder.
  • Put all your components files inside the “app/components” folder.
  • All of your resources should go inside the “assets” folder.

2. Understand Scope in AngularJS

The scope is something which binds the HTML with the JavaScript. It’s an object created by AngularJS to access the methods and properties of the controllers and directives. It includes a lot of handy information which is quite useful for debugging purpose.

  • To access scope, first of all, you need to get to the target element. It is easily doable with the help of Chrome’s dev tools. Just inspect the web element and switch to the console tab.
  • There you can type $($0) or angular.element($0) to print the element. And then can use $($0).scope() to get to the scope object.
  • With the help of scope, you can know its whereabouts like its parents [$($0).scope().$parent] or parents of parents [$($0).scope().$parent.$parent] etc.
  • If the selected element is a directive having isolate scope, then use $($0).isolateScope() to determine its scope.
  • Also, using the $($0).scope().<Property Name> will return the value of that property.
  • If you wish to check if the scope includes a property or not, then use the $($0).scope().hasOwnProperty(‘<Property Name>’).

3. Restrain from doing DOM Manipulation.

You should not carry out any DOM Manipulations inside controllers, services or anywhere else. However, you can have them working in the directives. Or the best is to avoid them as whenever there is any, else AngularJS will trigger events to maintain the application state. And It’ll lead to extra overhead for the application.

4. Use Service to share data between controllers.

Sometimes, you have two or more views in different routes that need access to some status variable. Or you may have multiple components which need access to the same piece of data.

5. Don’t use controllers for presentation logic.

The recommended development model in AngularJS is the MVC. It consists of a model, view, and controller. When you add presentation code in the controller, then you are breaking the integrity of the layers. Also, it could lead to unmanageable code. And it would become hard for other developers to debug. So, if you require a change in any HTML element or any DOM manipulation, then you should do it in the presentation layer.

6. Use Track By for quickly displaying list items.

You can control the frequency of rendering lists by using the Track By feature. Otherwise, displaying the list will require the DOM to reload for every item in the list.

7. Adapt ControllerAs approach.

In spite of using the scope as a container, it’s better to use a controller as itself.

For your information, in controllers, it is no longer suggested to use the “$scope” variable. But we can assign everything to a controller object like this.text=” “. And in HTML templates, we should just set a name for our controller variable.

Angular JS Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

8. Integrate Less to produce CSS.

LESS, which is a CSS pre-processor and provides features like mixins, operators, and functions. Many developers recommend the use of Less for web development with AngularJS. While working with it, there are a lot of things which you can achieve.

  • It offers high-level styling syntax to allow web developers to produce advanced CSS.
  • LESS preprocessor compiles into standard CSS before the browser begins rendering a web page.
  • Pre-compiled CSS files can be easily transferred to a production web server.

9. Use Built-in validations in AngularJS.

AngularJS embeds an excellent feature of auto-validating your form. And eventually, this ability can become the backbone of any application that receives user inputs.

Usually, the validation of a form goes through a chain of code blocks. They include multiple “if, else if…” which leads to undesired complexity. In this approach, the user has to submit the form a no. of times to handle one validation error after the other.

However, AngularJS brings a different way of form validation which happens as the user fills it out. And all of these validations are inherent in Angular JS in the form of directives.

10. Avoid filters with large arrays.

Filters run on each digest loop and create a new array every time they execute. In such cases, prefer to watch your list and do filtering upon detecting a change.

11. How to detect if property changes.

Here is the sample code that monitors a property. It’ll print logs on the console.

12. Use multiple controllers in separate modules.

If you have multiple controllers in separate modules, then you can still use them inside a single module. However, you’ll need to include them as dependencies of your main module.

Summary – AngularJS Tips for Beginners.

The above tips can be a good foundation for your future applications. These will help you improve skills and grow your knowledge in AngularJS. Also, you can improve productivity by turning your focus on the core business logic of your project.

Finally, we wish that you now have the required tools to start considering better approaches to design state of the art AngularJS applications.

Are you looking training with Right Jobs?

Contact Us

Popular Courses