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 个解决方案
#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.
一种很好的方法应该是,当您定义指令时,您可以将bindToController设置为true并在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.
你的控制器类在这里是角控制器。
#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.
一种很好的方法应该是,当您定义指令时,您可以将bindToController设置为true并在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.
你的控制器类在这里是角控制器。