10
votes

i like to make a custom component using directive. i checked lot of tutorials and its get confusing me can anyone explain how a directive works. the component i am planing to make is

<shout-list></shout-list>

the template for shout list will be like this

<div class="shout" ng-repeat="shout in shouts">
    <p>{{shout.message}}</p>
    <img src="media/images/delete.png" width="32" height="32" ng-click="deleteShout({{$index}},'{{shout._id}}')"/>
</div> 
1
Short videos from egghead.io helps me to understand directives. And videos from blogpost About those directives from official AngularJS blog.Maxim Ponomarev
i watched the video but i am confused in when to use compiler and linkerJaison Justus
In common words: compiler should used for modify the template, linker for binding data to the compiled templateMaxim Ponomarev
@MaximPonomarev in which case do you use compiler and linker? can you specify on situation when we are gonna use it..Jaison Justus
I wrote a blog article to get people started writing directives: seanhess.github.io/2013/10/14/angularjs-directive-design.htmlSean Clark Hess

1 Answers

16
votes

Here's your directive, with some inline comments:

angular.module( 'directives', [] ).directive( 'shoutList', function () {
  return {
    restrict: 'E', // allow as an element; the default is only an attribute
    scope: {       // create an isolate scope
      shouts: '='  // map the var in the shouts attribute to this scope
    },
    templateUrl: 'templates/shoutList.html', // load the template file
    controller: function ( $scope ) {
      // we declare a your function for use in the view
      $scope.deleteShout = function ( idx, id ) {
        // do whatever
      };
    }
  };
});

And the template file:

<div class="shout" ng-repeat="shout in shouts">
  <p>{{shout.message}}</p>
  <img src="media/images/delete.png" width="32" height="32" 
    ng-click="deleteShout({{$index}},'{{shout._id}}')" />
</div> 

And now you can use it in your code, like so:

Controller:

.controller( 'MainCtrl', function ( $scope ) {
  $scope.myShouts = // ...
});

View:

<shout-list shouts="myShouts"></shout-list>

Hope this helps!