Our first element directive will not do much: it will just calculate 2+2
and will be called in html like this:
<my-calculator></my-calculator>
Notice the name of the directive is myCalculator
(in CamelCase), but in html it's used as my-calculator
(in lisp-case).
Since we want our directive to be used as html element, we will use restrict: 'E'
.
Every directive has the template which will be compiled and inserted. Our directive is very simple, so we will insert our html as string into a template
parameter.
// directives/my-calculator.js
angular.module('exampleApp', [])
.directive('myCalculator', function() {
return {
restrict: 'E',
template: '<span> My directive can calculate 2+2: {{2+2}} </span>'
};
});
HTML
<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="my-calculator.js"></script>
</head>
<body>
Here is my first directive:
<my-calculator></my-calculator>
</body>
</html>
The result will look like this:
Here is my first directive: My directive can calculate 2+2: 4
If you want to play with the live example, go to plunkr.