javascript - 以不同的方式使用 Angular 指令

标签 javascript angularjs angularjs-directive angular-services

我正在使用这样的 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 将正常运行。

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

我的问题是如何做到这一点。我尝试在指令中注入(inject)服务,但导致未定义。

谢谢。

最佳答案

一个好的方法应该是,当您定义指令时,可以将 bindToController 设置为 true 并纠正 Controller 类中的逻辑。您可以将您的服务注入(inject)该 Controller 。

例如。

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

yourControllerClass 这里是 Angular Controller 。

关于javascript - 以不同的方式使用 Angular 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001795/

相关文章:

javascript - 我如何在使用 ng-repeat 循环访问相同的 json 时按 json 的属性之一进行排序?

HTML 未在 Jade 内呈现

angularjs - Angular JS : Load CSS and JS files dynamically

javascript - 如何优化在 canvas JS 上绘制大量元素?

javascript - 使用 Fotorama api 自定义缩略图和标题

javascript - 无法读取未定义 jquery 滚动的顶部

javascript - 当我导航回 jQuery Flipbook 时,导航按钮未显示

javascript - ui.router 改变状态,但 ui-view 不显示任何内容?

angularjs - Angular 等待父 Controller

javascript - 在 Angularjs 中使用 "peek through"处理 neSTLed ng-click