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">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular-resource.min.js"></script>
    <script>
      app = angular.module('app', ['ngResource']);
      app.directive('icon', function factory() {
        return {
          restrict: 'E',
          scope: {
            name: '@'
          },
          template:
            '<div class="icon">' +
            '  <img src="http://cdn1.iconfinder.com/data/icons/fugue/icon_shadowless/{{name}}.png"/>' +
            '  <div class="icon-name" ng-transclude>' + '</div>' +
            '</div>',
          replace: true,
          transclude: true
        }
      });
    </script>

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

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="http://cdn1.iconfinder.com/data/icons/fugue/icon_shadowless/arrow_circle_225.png">
  <div class="icon-name" ng-transclude="">
    <span class="ng-scope">
      Arrow Circle
    </span>
  </div>
</div>
Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: