2

i'm using Angular directives like this:

'use strict';
var eventDirective = {

    /**
    * Initialize event directive and return the link
    * calling all nested methods.
    *
    */
    init: function($scope, $element) {
        var that = this;

        return {
            link: function(scope) {
                scope.$watch('events', function() {
                    if (scope.events === undefined) {
                        return;
                    }

                    /**
                    * Every time the user access the event page, this methods
                    * will be called.
                    *
                    */
                    __TableSorter__.init($element);
                });
            },
            restrict: 'E'
        };
    },

    __TableSorter__: {
        init: function(element) {
            console.log(element) // PRINTS ELEMENT
        }
    }
};


angular
    .module('adminApp')
    .directive('eventDirective', eventDirective.init.bind(eventDirective));

To illustrate I created this simple example. The TableSorter will run normally.

The problem is when I have several scripts, the code is too large. Is there any way to solve this? Maybe put scripts elsewhere as factories or services ?

My question is how to do this. I tried to inject a service within the directive but was resulting in undefined.

Thanks.

1 Answer 1

3

A good way to do should be, when you define your directive, you can set bindToController to true and right your logic inside a controller class. You may inject your services to that controller.

For example.

myModule.directive('directiveName', function factory(injectables) {
  var directiveDefinitionObject = {
    template: '<div></div>',
    scope: {},
    controllerAs: 'yourControllerClass',
    bindToController: true
  };
  return directiveDefinitionObject;
});

yourControllerClass is angular controller here.

Sign up to request clarification or add additional context in comments.

3 Comments

hm, i'm very new in Angular. Do you know any tutorial that explain this?
I have updated my answer, and here are the docs docs.angularjs.org/api/ng/service/$compile. Look for bindToController on the page.
Get it! Let me ask you something. What do you think about doing that? What's you opinion?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.