简体   繁体   中英

Using Angular Directives with different approach

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM