First Directive

AngularJS - First DirectiveAngularJS Video Tutorial by John Lindquist

Directives might just be the killer feature of AngularJS. Directives allow us to extend the grammar of the web through reusable HTML elements, attributes, and classes.


The ability to reply to discussions is limited to PRO subscribers. Want to join in the discussion? Click here to subscribe now.

egghead.io comment guidelines

egghead.io
Avatar

Directives might just be the killer feature of AngularJS. Directives allow us to extend the grammar of the web through reusable HTML elements, attributes, and classes.


index.html

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="utf-8">
  <title>Egghead Videos</title>
  <link rel="stylesheet" href="vendor/foundation/foundation.min.css">
</head>
<body>

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

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
  <script type="text/javascript" src="app/js/main.js"></script>
</body>
</html>

main.js

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

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

John Lindquist: Let's see what it takes to create our very first directive. We're going to create in our main JS an app. We'll just call it "Super Hero," and no dependencies. Then we'll just say, "App Directive," and this is one of those syntaxes you just need to memorize. We'll create a Superman directive, and from this call back, we'll return object with property called "restrict," and we'll restrict it to capital E which is Element.

We'll say this is a template. Let's check dates to mail, so I can use a Zen Coding or Emmet. Div and we'll say, "Here I am to save the day." Now that we have a super hero module with a Superman directive which is restricted to E, we can jump into our index creator app, which is superhero, and create our Element here, which is using our directive called Superman.

Once we refreshed this and check out over here, you can see it says, "Here I am to save the day." That's really all there is to writing your very first directive. We'll get into the details of what's going on here in future videos, but basically as soon as you have an app, you can attach directives to that app or that module, and in your HTML, you basically make sure you define your Elements inside of your app. It's not going to work if you put this outside of that, because it's only going to work in the scope that that app will allow.

Tech logo bar

Don't miss out on the latest PRO lessons.

Get Your PRO Subscription Now

Because you like code... not PowerPoint slides.