AngularJS Tutorial - What are Directives








A directive is a way to extend HTML. Angular allows us to extend HTML by adding attributes, elements or comments.

Example

The following code outputs the content as you type in the text box.


<!DOCTYPE html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js">
</script><!--from   w w w  .j a  va  2  s  .co  m-->
</head>
<body>
    Name:<input type='text' ng-model='name'/>
    {{name}}
</body>
</html>

The code above is rendered as follows:





Note

The code above used a very basic Angular directive.

Rather than <html> at the top we have <html ng-app>.

ng- is an Angular directive.

Later the code defined another directive called ng-model.

ng-model adds a property called "name" into a view model. The view model in AngularJS is "the scope".

View model, or ViewModel, is concept from MVC pattern. It is basically a model for the view.

In the code above ng-model creates an empty ViewModel and fill it with a name property.

{{name}} is a data binding expression.