gpt4 book ai didi

javascript - 如何将 Angular Directive(指令)的链接和 Controller 传递给它

转载 作者:行者123 更新时间:2023-11-28 15:31:49 27 4
gpt4 key购买 nike

假设我有一个直接的指令:

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
}
}
}
}
]);

上面的代码有太多的缩进和拥挤,至少对我来说,它很难阅读,而且使用起来也不愉快。

相反,我想将 linksomeEmbeddedFunction 移出并调用它们。所以类似这样的事情:

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
}
]);

问题是 MyService1MyService2 没有传递给链接函数(即,如果我只有一个具有 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);
}

最佳答案

正如您所观察到的,调用非标准链接函数的唯一方法是在“标准”链接函数中手动执行此操作。

link: function(scope, element, attrs) { 
link(scope, element, attrs, MyService1, MyService2);
}

这是因为链接函数不像 Angular 中的其他函数那样被注入(inject)。相反,它总是获取相同系列的参数(无论您如何称呼函数参数):

  1. 范围
  2. 元素(作为 angular.element() 实例)
  3. attrs 对象
  4. 需要的数组或单个 Controller 实例
  5. 嵌入函数(如果您的指令使用嵌入)

没有别的了。

关于javascript - 如何将 Angular Directive(指令)的链接和 Controller 传递给它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007415/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com