![](/img/trans.png)
[英]How to define an angular directive inside an angular directive's link function?
[英]How to pass the angular's directive's link and controller to it
假設我有一個直接的指令:
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
的鏈接函數scope, element, attrs
那么上面的代碼就可以了)。 我也該如何傳遞這些變量?
我試圖將函數調用為link: link(scope, element, attrs, MyService1, MyService2)
但是隨后它說scope, element, attrs
是未定義的。
請注意,我意識到someEmbeddedFunction
現在可以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中的其他函數一樣被注入。 取而代之的是,它總是獲得相同的系列參數(無論您如何稱呼函數參數):
angular.element()
實例) attrs
對象 require
的數組或單個控制器實例 沒有其他的。
我使用此方案來使其簡單易讀:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.