我正在使用这样的 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/