AngularJS – Directives (1)

I couldn’t understand how/when to use directives in the first place. So, I’ve tried on the above video. It has nice explanations and examples. As I understood, directive brings a function into HTML world through extending a tag or its attributes. It’s a similar concept as functions in standard programming languages, which provides a way seperating out a duplicated logics into shared templates.

What I’ve learned about directives are are as follows.

  • “template” attributes allows to directly defining templating HTML tags, or you can use “templateUrl” for rendering partials in the file.
  • If “transclude” is set true, you can include “ng-tranclude” in the template.
  • Setting “scope” attribute makes own scope in the directive. If setting a attribute with “@” mark, allows to read scope attributes.

And, the following is a exercise I’ve tried so far.

<html ng-app="app">
    <script src=""></script>
    <script src=""></script>
      app = angular.module('app', ['ngResource']);
      app.directive('icon', function factory() {
        return {
          restrict: 'E',
          scope: {
            name: '@'
            '<div class="icon">' +
            '  <img src="{{name}}.png"/>' +
            '  <div class="icon-name" ng-transclude>' + '</div>' +
          replace: true,
          transclude: true

    <style type="text/css">
      .icon-name {
        display: inline;
      <icon name="arrow_circle_225">Arrow Circle</icon>
      <icon name="broom">Broom</icon>

The <icon> tag is expanded as follows, and it shows icon image along with the name inside the <icon> tag.

<div class="icon" name="arrow_circle_225">
  <img src="">
  <div class="icon-name" ng-transclude="">
    <span class="ng-scope">
      Arrow Circle

Posted on February 24, 2013, in JavaScript. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: