簡體   English   中英

如何將角度指令的鏈接和控制器傳遞給它

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

上面的代碼非常縮進,而且很擁擠,至少對於我來說,很難閱讀且不喜歡使用。

相反,我想移出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的鏈接函數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中的其他函數一樣被注入。 取而代之的是,它總是獲得相同的系列參數(無論您如何稱呼函數參數):

  1. 范圍
  2. 元素(作為angular.element()實例)
  3. attrs對象
  4. require的數組或單個控制器實例
  5. 包含函數(如果您的指令使用包含)

沒有其他的。

我使用此方案來使其簡單易讀:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM