AngularJS - First Directive

Let’s see what it takes to create our very first directive. We’re going to create in our main.js an app called superhero with no dependencies. Then we’ll just say app.directive, and create a superman directive. The first parameter will be the name of the directive and the second will be a function for a callback. From this callback, we’ll return an object with a property called “restrict” which will restrict this directive to Elements. The object will also have the property “template” for specifying the HTML for our directive. For our template, we’ll make a div and we’ll say “Here I am to save the day”

var app = angular.module("superhero", [])

app.directive("superman", function() {
  return {
    restrict: "E",
    template: "<div> Here I am to save the day </div>"
  }
})

Now that we have a superhero module with a superman directive which is restricted to “E”, we can jump into our index, create our superhero app, and create our element here, which is the superman directive.

<div ng-app="superhero">
  <superman></superman>
</div>

Once we load the page and check it out, you can see it says, “Here I am to save the day” and that’s all there really is to writing your very first directive.

We’ll get into the details of what’s going on here in another lesson. Basically, as soon as you have an app you can attach directives to that app or module, and in your HTML make sure you define your elements inside of your app.