说我有一个直接的指令:
angular
.module('myApp')
.directive('myDiv', ['MyService1', 'MyService2',
function(MyService1, MyService2) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.myVars = MyService1.generateSomeList();
MyService2.runSomeCommands();
// Do a lot more codes here
// Lines and Lines
// Now run some embedded function here
someEmbeddedFunction();
function someEmbeddedFunction()
{
// More embedding
// This code is really getting nasty
}
}
}
}
]);
上面的代码有很多缩进和拥挤,至少对我来说,很难阅读和不愉快的工作。
相反,我想将link
和someEmbeddedFunction
移出并调用它们。所以有类似的东西:
function link(scope, element, attrs, MyService1, MyService2)
{
scope.myVars = MyService1.generateSomeList();
MyService2.runSomeCommands();
// Do a lot more codes here
// Lines and Lines
// Now run some embedded function here
someEmbeddedFunction();
}
function someEmbeddedFunction()
{
// This is much nicer and less tabbing involved
}
angular
.module('myApp')
.directive('myDiv', ['MyService1', 'MyService2',
function(MyService1, MyService2) {
return {
restrict: 'E',
link: link // This is line that I need to get it to work
}
]);
问题是MyService1
和MyService2
没有传递给链接函数(即如果我只有scope, element, attrs
的链接函数,那么上面的代码就可以了。我怎样才能传递这些变量?
我尝试将该函数调用为link: link(scope, element, attrs, MyService1, MyService2)
,但后来说scope, element, attrs
未定义。
注意我意识到someEmbeddedFunction
现在可以毫无问题地移出。这仅用于演示目的。
修改
我能想到的唯一方法是通过这种方式从指令中调用link
函数:
link: function(scope, element, attrs) {
link(scope, element, attrs, MyService1, MyService2);
}
答案 0 :(得分:2)
正如您所观察到的,调用非标准链接功能的唯一方法是在“标准”链接功能中手动执行此操作。
即
link: function(scope, element, attrs) {
link(scope, element, attrs, MyService1, MyService2);
}
这是因为链接函数没有像Angular中的其他函数那样被注入。相反,它始终获得相同的参数序列(无论您调用函数参数):
angular.element()
实例)attrs
对象require
d 别无其他。
答案 1 :(得分:2)
我使用这个方案来保持简单和可读:
var awesomeDir = function (MyService, MyAnotherService) {
var someEmbeddedFunction = function () {
MyService.doStuff();
};
var link = function ($scope, $elem, $attrs) {
someEmbeddedFunction();
};
return {
template: '<div>...</div>',
replace: true,
restrict: 'E',
link: link
};
};
awesomeDir.$inject = ['MyService', 'MyAnotherService'];
app.directive('awesomeDir', awesomeDir);