1

I want to write a simple directive that displays a list of datas from the parent.

The parent controller has something like $scope.datas = [1,2,3,4]

How should I write the directive ?

  • Use isolated scopes and have something like scope : { display : '=' }

  • Use children scope and directly reference $scope.datas ?? I found that ugly. I would like to reuse the directive so I want to pass an attribute to indicate which parent field should be used. In other words, I'd like to say to the directives that my datas are either in $scope.datas or $scope.dumpthat.

Thanks !

user2944669
  • 165
  • 10

1 Answers1

1

I would use an isolated scope for this. You could use the parent scope properties in the child, but since Angular uses prototypical inheritance you would have to be careful about how you go about (and what you go about) accessing.

Here is a simple directive:

HTML

<display-directive display="datas">Datas are:</display-directive>

Directive

app.directive("displayDirective", function(...) {
    return {
         restrict: "E",

         scope: {
             display: "=",
         },

         // Transclude will take the inner html of your directive and add it to
         // any div which contains the ng-transclude directive
         transclude: true,

         // replace will swap out the inner html of the directive scope with
         // the template you assign
         replace: true,

         template: [
             "<div class='data-class'>",
             "    <div class='data-prefix' ng-transclude></div>",
             "    {{ display }}",
             "</div>",
         ].join("\n"),

         link: function(scope, element, attributes) {
             // Initialize your directive here!
         }),
     };
});
sabhiram
  • 897
  • 7
  • 10