Create an Angular directive

angularI spent some time playing with angular.js directives and try to understand what option you should not forget to make it works, this is detailing the result of these search.

 

Create a custom tag

An angular directive is a way to create your own html taglike this:

<google-photo></google-photo>

To declare a such tag, you will have to create a .directive in your controller. like this :

.directive('googlePhoto', function () {
        return {
            restrict: 'E',
            scope: {
                mytags: '=tags'
            },
            templateUrl: 'views/google-photo.html',
            link: function(scope, element, attrs) {
                console.log("I'm in !");

            }
        };
    })

Here we have the following element :

  • The directive name ‘googlePhoto’ is matching the tag name google-photo. This is a naming convention.
  • restrict “E” indicates you want to create a new tag <name-of-the-directive>
  • scope is linking the attribute “tags” to a local variable mytags
  • templateUrl is a html file containing what will replace your tag
  • link is the function to execute when the tag is built.

The templateUrl file will be like this :

<div>
    -- {{ mytags.name }} --
</div>

The mytag variable will match the variable indicated in the main html file in the tags attribute like this :

<div class="google-photo" tags="myVariable"></div>

So this means the “$scope.myVariable” variable will be match to “mytag” in the tag you just created.

Customize an object

If you want to change a property of an element, apparently the more easiest way is to customize a standard element like a div using a directive:

   .directive('googlePhoto', function (Google) {
        return {
            restrict: 'CA',
            scope: {
                mytags: '=tags'
            },
            templateUrl: 'views/google-photo.html',
            link: function(scope, element, attrs) {
                  element.css({
                      'background': 'url(' + data.responseData.results[index].url + ') no-repeat'
                  });
             }
        };
    })

Here we have:

  • restrict ‘CA’ indicates you can use <div class=”google-photo”> or <div google-photo> in your html code to refer this directive.

Your template have not changed.

Now you html code looks like :

  <div class="google-photo" tags="stags">Hello</div>

In your js code, element refers to this div and you can modify it.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.