簡體   English   中英

將外部函數傳遞給角度指令

[英]Pass External Function into Angular Directive

我正在努力尋找一種將外部/范圍外/非角度函數傳遞給指令的優雅方法。 到目前為止,我唯一能看到的方法是將函數名稱作為字符串傳遞給angular,然后使用eval,效果似乎不太好。 這是在Plunker上的示例http://plnkr.co/edit/L9GGDkxwh4IGNufXB8yg?p=preview

在范圍內使用extFunc:'&'僅適用於范圍內的函數,因此不適用於我。

有更好的方法嗎? 我意識到在我的示例中,只是將函數包含在指令或控制器中,但這並不總是實用的。

<script>
function nonAngularFunction( someText ) {
    alert( someText );
}
<script>

<my-directive ext-func="nonAngularFunction('Hi there')" ></my-directive>

抱歉,如果您已經問過這個問題,但是我在任何地方都找不到解決方案。

我將此功能作為服務導入Angular的世界:

/* global nonAngularFunction:false */
angular.module('aModuleName', [])
    .value('nonAngularFunction', nonAngularFunction);

然后,您可以使用注入並將函數導入到您的范圍:

// ... in your directive or controller
angular.module('maybeAnotherModule', ['aModuleName'])
    .controller('YourController', ['$scope', 'nonAngularFunction',
        function ($scope, nonAngularFunction) {

            $scope.nonAngularFunction = nonAngularFunction;
        }]);

應該工作(我還沒有測試)。

編輯:當有許多外部功能時的替代方法

eval不是實際的解決方案,因為它無法訪問您的范圍。

您可以將很多函數導入Angular中,例如

angular.module('aModuleName', [])
    .value('myHorribleLib', {
        'oneFunction': oneFunction,
        'Constructor1': Constructor1,
        ...
    });

然后,您必須通過$scope.legacyLib = myHorribleLib使它們可用,並將其與前綴一起使用: ng-click="legacyLib.oneFunction('hello')" 有點冗長,但是您要留意遺產。

或者,您可以使用以下方法擴展$rootScope (或頂級作用域):

angular.module('aModuleName', [])
    .run(['$rootScope', '$window', function ($rootScope, $window) {
        'oneFunction Constructor1 anotherFunction ...'
           .split(' ').forEach(function (f) {
               $rootScope[f] = $window[f];
           });
    }]);

我並不是說這是一個超級干凈的解決方案,但是通過這種方式,您可以將舊版庫的功能公開給Angular作用域。 現在,它們應該可以在正常的ng-click等環境中工作,並可以訪問您的示波器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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