1- If you want reusable HTML components
<my-widget>
2- If you want reusable html behaviour
<div ng-click="...">
3- If you want to wrap a jQuery plugin
<div ui-date></div>
4- Almost any time you want to interface with DOM
1- Create a module for your directive ( Best Practice )
angular.module("MyDirective", []);
2- Load the module in your app
angular.module("MyApp", ["MyDirective"]);
3- Register your directive
angular.module("MyDirective").directive("myWidget", function(){
return{
restrict: "EA",
...
};
});
4- Use directive in your HTML
<div my-widget></div>
angular.module("MyApp").directive("selectOnFocus", function(){
return{
restrict: "A",
link: function(scope, elm, attrs){
elm.on("click", function(){
this.select();
});
}
};
});
Uses...
<input type="text" value="Hello World" select-on-focus />