2017-03-31 39 views
0

我試圖實現一個基於角色的訪問控制系統,其中允許的資源將在登錄後從服務器加載。我可以設法使用原始JavaScript代碼進行檢查。Angular TypeScript指令的鏈接方法不會被調用

angular.module('app').directive('accessControl', 
[ 
    'AuthService', function (authService) { 
     return { 
      restrict: 'A', 
      scope: "=", 
      link: function (scope, element, attrs) { 
       scope.canShow = function(resource) { 
        var allowedResources = authService.accountInfo.resources; 
        return allowedResources.indexOf(resource) !== -1; 
       } 

      } 
     } 
    } 
]); 

但因爲我的整個應用程序是打字稿,我一直在努力使純打字稿的指令,但不幸的是,我不能這樣做。這是我的TS代碼。

export class AccessControl implements ng.IDirective { 

    public authService: App.AuthService; 
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void; 

    constructor(authService: App.AuthService) { 
     this.authService = authService; 
     console.log('authservice: ', authService); 
     AccessControl.prototype.link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => { 
      scope["canShow"] = function (resource: string) { 
       // some logic 
       console.log('can show' + resource); 
       return true; 
      }; 
     }; 
    } 

    public static factory(): ng.IDirectiveFactory { 
     var directive = (authService: App.AuthService) => { 
      return new AccessControl(authService); 
     }; 

     directive['$inject'] = ['AuthService']; 
     return directive; 
    } 

    restrict = "A"; 
    scope: "="; 
} 

angular.module('app').directive('accessControl', AccessControl.factory()); 

鏈接函數永遠不會被調用。 任何幫助或指針將不勝感激。

回答

0

我們一直宣稱link只是該類的公共功能。除非您使用隔離範圍(在這種情況下,它將是每個範圍變量或特定方法通過的方法),否則您的指令類中不需要公開scope變量。此外,您可以直接在directive上設置$inject,而不使用您正在使用的括號屬性符號。以下是我們如何使用TypeScript創建指令:

namespace app.directives { 
    export class AccessControl implements ng.IDirective { 

     public restrict = "A"; 

     constructor(private authService: App.AuthService) { 
      console.log("authservice: ", this.authService); 
     } 

     public link(scope: ng.IScope, 
        element: ng.IAugmentedJQuery, 
        attrs: ng.IAttributes) { 
      console.log("in link function of directive", scope); 
     } 

     public static factory(): ng.IDirectiveFactory { 
      var directive = (authService: App.AuthService) => { 
       return new AccessControl(authService); 
      }; 

      directive.$inject = ["AuthService"]; 
      return directive; 
     } 
    } 

    angular.module("app") 
     .directive("accessControl", AccessControl.factory()); 
}