2016-04-29 45 views
1

我已經使用typescript編寫了一個指令。下面是我的指示。

'use strict'; 

    module App.Directives { 

    interface IPageModal extends ng.IDirective { 
    } 

    interface IPageModalScope extends ng.IScope { 

    } 

    class PageModal implements IPageModal { 
     static directiveId: string = 'pageModal'; 
     restrict: string = "A"; 

     constructor(private $parse: ng.IParseService) { 

     } 

     link = (scope: IPageModalScope, element, attrs) => { 

      element.click((event) => { 
       event.preventDefault(); 

       var options = { 
        backdrop: 'static', 
        keyboard: false 
       }; 

       event.openModal = function() { 
        $('#' + attrs['targetModal']).modal(options); 
       }; 
       event.showModal = function() { 
        $('#' + attrs['targetModal']).modal('show'); 
       }; 
       event.closeModal = function() { 
        $('#' + attrs['targetModal']).modal('hide'); 
       }; 
       var fn = this.$parse(attrs['pageModal']); 
       fn(scope, { $event: event }); 
      }); 
     } 
    } 

    //References angular app 
    app.directive(PageModal.directiveId, ['$parse', $parse => new PageModal($parse)]); 
} 

在使用HTML

<button class="btn blue-grey-900" target-modal="emplpyeeViewModal" page-modal="vm.addEmployee($event)"> 
    <i class="icon-plus m-b-xs"></i> 
</button> 

使用的控制器

addEmployee($event) { 
    $event.openModal(); 
}; 

此行不起作用。 var fn = this.$parse(attrs['pageModal']);。我不明白什麼是錯的。錯誤是

this。$ parse is undefined。 和服務被稱爲兩次

+0

此語法'['$ parse',($ parse)=> new PageModal($ parse)]'看起來很尷尬。 Angular已經迫使你進行時髦的數組注入,你創建了一個具有注入服務屬性的類,並且另外你創建了2次:'($ parse)=> new PageModal($ parse)'。如果你將注入10個服務會怎麼樣? 40次列出相同的名稱? – smnbbrv

回答

0

這是很簡單的:你的this是不是你的class'es範圍,因爲function openmodal(event) {定義了自己。

在類級別聲明該函數或使用箭頭函數(例如,

link = (scope: IPageModalScope, element, attrs) => { 
    element.click((event) => { 
     event.preventDefault(); 

     var options = { 
      backdrop: 'static', 
      keyboard: false 
     }; 

     event.openModal = function() { 
      $('#' + attrs['targetModal']).modal(options); 
     }; 
     event.showModal = function() { 
      $('#' + attrs['targetModal']).modal('show'); 
     }; 
     event.closeModal = function() { 
      $('#' + attrs['targetModal']).modal('hide'); 
     }; 
     var fn = this.$parse(attrs['pageModal']);//does not work here 
     fn(scope, { $event: event }); 
    }); 
} 
+0

同樣的錯誤this。$ parse is undefined。 – Shohel

+0

嗨,這裏出現新問題,鏈接函數被調用兩次 – Shohel