AngularJS - Introduction

By xngo on August 18, 2019

AngularJS is a JavaScript web development framework. It transforms the good old HTML into a template language by using directives. And, it follows a slightly modified version of the Model-View-Controller(MVC) design pattern. The Controller part of the MVC has been replaced with Whatever as AngularJS is not strictly bounded to the Controller concept but it can create any kind of linking between the Model and the View.

This tutorial will show how to create a simple web page using AngularJS.

AngularJS directives

AngularJS extends HTML with ng-directives. Directives are HTML attributes with an ng prefix. Here is example using different directives. The code below will display back whatever you type in the input field.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
    <title>Angular - Hello World</title>
</head>
<body>
 
    <div ng-app="">
        <p>Type something in <input type="text" ng-model="myVariable"></p>
        <p>You have typed <span ng-bind="myVariable"></span>.</p>
    </div>
 
</body>
</html>
  • ng-app directive defines that the <div> element is the start of an AngularJS application. For the time being, ignore that it has an empty value.
  • ng-model directive binds the value of the input field to the variable called myVariable. Think of ng-model as a way to declare the variable myVariable.
  • ng-bind directive binds the content of the <span> element to the variable called myVariable. Think of ng-bind as a way to link the variable myVariable.

Output

AngularJS - Hello World - Ouput

Directive prefix: data-ng vs ng

For the directives, it is recommended to use data-ng prefix instead of ng prefix. Some HTML validators will throw an error for attributes with ng prefix but not for data-ng prefix. Besides, according to the HTML5 specification, the proper way to add a custom attribute is to prefix it with data-.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.