Directives can be used in four ways
- As elements: <hello-world></hello-world >
- As attributes: <input type=”text” hello-world />
- As classes: <input type=”text” class=”hello-world”/>
- As comments : <!–directive: hello-world –>
Usually we use directives as elements and attributes. Let’s see that how we can create directives using an example
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/angular.js"></script> <script> angular.module("myApp", []).directive("helloWorld", function () { return { restrict: 'AEC', replace: true, template: '<h3>Hi Dear Hello World</h3>' }; }); </script> </head> <body ng-app="myApp"> <hello-world></hello-world> <div hello:world></div> </body> </html>
In above example we created a angular module named “myApp” in html body tag and getting its reference into <script></script>. Here I am not briefing about angular modules we will discuss it later. First Argument of angular.module is module name and other argument denote module dependencies. After it we are calling a directive method which is used to create custom directives.In this method first argument is custom directive name and second argument is callback function which is returning a custom directive object.Now we will discuss about object values.
Restrict: this parameter is shows that how How we can use this directive as (A-Attribute, E-Element, C-Class). We can skip any parameter if required.
Replace: this parameter shows that that html tag should be replaced or works as parent element.
Two values are possible.
- True: Its means that html element should be replaced with custom directive template.
- False: Its means that directive should be placed as child element
Template: It is compulsory argument which is adding custom html markup(here <h3>Hi Dear Hello World</h3>) here we can also place any other html file also .
Output :