0

I've a directive to create a list of elements to control pagination and filters, I use it in several points of my application.

I want to know what is the best way to add custom methods to the directive.

Example:

angular.module('example').directive('list', function () {
    return {
        scope: {
            elements: '=ngModel',
            filters: '=?'
        },
        restrict: 'E',
        transclude: true,
        templateUrl: '/static/templates/list.html',
        controller: function () {
            // Some stuff of pagination and filters functions
        }
    }
}

My directive template looks like:

<div class="list">
    <!-- Pagination stuff -->

    <div ng-transclude></div>

    <!-- Pagination stuff -->
</div>

And I use the directive like this:

<list elements="elements">
    <div ng-controller="CustomMethodsController">
        <div class="col-xs-6">
            {{result.element_1}}
        </div>
        <div class="col-xs-6">
            {{result.element_2}}
        </div>
    </div>
</list>

I don't know whether create a controller inside a directive is a good practice or there's a better way to achieve this.

Thanks in advance.

Sergio
  • 106
  • 1
  • 7

2 Answers2

0

You have already specified a controller in the directive destination.You need to use that:

     scope: {
        elements: '=ngModel',
        filters: '=?'
    },
    restrict: 'E',
    transclude: true,
    templateUrl: '/static/templates/list.html',
    **controller: function () {
        // Some stuff of pagination and filters functions
    }**

But yeah you can give controllers inside directives.Although its better if you are doing that you can have nested directives.

  • But if I use the directive 6 times and each time I use it I need a custom method to specialize the work, Should I put all custom functions inside the directive? It is not better specialize that functions in other controller? – Sergio Apr 15 '16 at 08:50
  • That's what I was saying. You can have a service with functions. You inject it in the controllers you need and use it's functions. – Fernando de Bem Apr 15 '16 at 08:56
  • Yes i agree you can have a service or a factory for that.All your binding logic should be inside the controller whereas the business logic you can have in your service/factory. – antish Gajwani Apr 15 '16 at 09:30
0

If it's something you are going to share across multiple controllers, you can create a service and inject it into the controllers that uses it.

Fernando de Bem
  • 116
  • 1
  • 6