Skip to content

Instantly share code, notes, and snippets.

@bdsexton
Created November 27, 2014 10:13
Show Gist options
  • Save bdsexton/b596a0e1faec8b001d24 to your computer and use it in GitHub Desktop.
Save bdsexton/b596a0e1faec8b001d24 to your computer and use it in GitHub Desktop.
An AngularJS Directive via Isolated Module JavaScript
(function() {
/*
An AngularJS Directive via Isolated Module JavaScript
This is just a simple example of an AngularJS module that defines a
directive within an immediately invoked function expression, which can
be stored in and loaded from a separate file for clear, lean code
organization and easy distribution.
------------------------------------------------------------------------
Brian Sexton
http://www.briansexton.com/
bdsexton's Gists
https://gist.github.com/bdsexton
------------------------------------------------------------------------
Usage
Script-loading in HTML:
<script src="path/to/angularjs-directive-module.js"></script>
Dependency-declaration in AngularJS app-module declaration:
angular.module("yourAppModule", ["demoModule"]);
Directive example in valid HTML5:
<p data-random-greeting></p>
------------------------------------------------------------------------
Note
If "scope" is not set for the directive, it will default to false and
the same greeting value will be used for all instances of the directive.
*/
angular.module("demoModule", [])
.directive("randomGreeting", function() {
var greetings = ["Hello!", "Hi!", "Hiya!", "Hail!", "Sup?", "What?!", "Hola!", "Bonjour!", "I used to be an adventurer like you. Then I took an arrow in the knee."];
return {
scope: true,
template: "{{greeting}}",
controller: function($scope) {
$scope.greeting = greetings[Math.floor(Math.random() * greetings.length)];
}
};
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment