使用不同方法的 Angular 指令

Using Angular Directives with different approach

我正在使用这样的 Angular 指令:

'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));

为了说明,我创建了这个简单的示例。 TableSorter 将 运行 正常。

问题是当我有几个脚本时,代码太大了。有什么办法可以解决这个问题吗?也许将脚本放在别处作为工厂或服务?

我的问题是如何做到这一点。我试图在指令中注入服务,但结果是未定义的。

谢谢。

一个好的方法应该是,当你定义你的指令时,你可以将 bindToController 设置为 true 并在控制器 class 中调整你的逻辑。您可以将您的服务注入该控制器。

例如

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

yourControllerClass 是 angular 控制器。