AngularJS – Directive(2)

A little more study on directive. Getting more understanding, but feeling more deeper complexity.

  • “compile” and “link” function have similar functionalities, but it becomes different when “ng-repeat” is applied along with it. “compile” is called only once, but “link” is called multiple times. It’s because compile is applied for its template. The “link” is applied for each instances. Use “link” instead of “compile” unless you want to modify template.
  • $ allows to monitor properties change and it provides a binding functionality for the variables. It can be used within the link functions or controllers.
  • $scope.apply can tell angular about the change occured outside of angular world (e.g. click event).

The following is some exercise I made. It’s just about updating image and text, when drop-down selection is changed.

<html ng-app="app">
    <script src=""></script>
    <script src=""></script>
      app = angular.module('app', ['ngResource']);
      app.directive('icon', function($parse) {
        return {
          link: function(scope, element, attr) {
            //watch scope.iconName through attr.icon variable, and update the text.
            scope.$watch(attr.icon, function(name) {
              element.text("current selection is '" + name + "'. Click this text to reset. ");

            //bind click event to update scope.iconName through attr.icon variable.
            element.bind('click', function() {
              scope.$apply(function() {
                $parse(attr.icon).assign(scope, scope.iconList[0]);

      function IconCtrl($scope) {
        // list of icon-name shown in the dropdown-list
        $scope.iconList = ["arrow_circle_225", "broom"];
        $scope.iconName = $scope.iconList[0];

        $scope.$watch('iconName', function(name) {
          //based on the drop-down selection, updates the icon image by updating $scope.iconUrl variable
          $scope.iconUrl = "" + $scope.iconName + ".png";

    <style type="text/css">
      .icon-name {
        display: inline;
  <body ng-controller="IconCtrl">
          ng-options="icon for icon in iconList">

      <img ng-src="{{iconUrl}}"/>
      <div icon="iconName" class="icon-name"/></div>

Posted on February 26, 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: