簡體   English   中英

如何將$ q傳遞給angular指令鏈接函數?

[英]How to pass $q to angular directive link function?

我需要使用$q我的指令的link功能。 我需要它來包裝由一個參數重新調整的可能的promise(參見下面的例子)。 但是,我不知道如何將$q依賴項傳遞給此函數。

angular.module('directives')
 .directive('myDirective', function() {
   return {
     scope: {
       onEvent: '&'
     }
     // ...
     link: function($scope, $element) {
       $scope.handleEvent() {
         $q.when($scope.onEvent()) {
            ...
         }
       }
     }
  }
}

只需將其添加為您的指令的依賴項,$ q將在鏈接函數中使用。 這是因為JavaScript的閉包

以下是基於您的代碼的示例。

angular.module('directives')
.directive('myDirective', ['$q', function($q) {
   return {
     scope: {
       onEvent: '&'
     }
     // ...
     link: function($scope, $element) {
       $scope.handleEvent() {
         $q.when($scope.onEvent()) {
           ...
         }
       }
     }
  }
}])

你不能直接注入鏈接函數,但你可以注入指令的工廠函數:

angular.module('directives')
 .directive('myDirective', function($q) {
   ...

或者,如果使用minifier,則使用數組語法進行注入。

var module = angular.module('directives');
module.directive('myDirective', ['$q', function($q) {
 ...
}]);

暫無
暫無

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

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