Skip to content

Instantly share code, notes, and snippets.

@hemantajax
Last active August 29, 2015 14:05
Show Gist options
  • Save hemantajax/e5515e68db27cff7b517 to your computer and use it in GitHub Desktop.
Save hemantajax/e5515e68db27cff7b517 to your computer and use it in GitHub Desktop.
Custom angular directive usecases

Angular Directive:

When to use directives:

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

Getting Started

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>

Custom Directive - selectOnFocus ( simulate browser address bar focus behavior )

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 />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment