2015-10-07 90 views
3

我正在使用AngularJS和TypeScript,現在我需要將視圖中的參數傳遞給控制器​​。這就是我如何試圖做到這一點(通過NG-INIT)的方式:Angular + TypeScript - 從視圖傳遞參數到控制器

<div class="col-md-9" ng-controller="MapIZSController" ng-init="init('IZS')"> 

"IZS"值應該傳遞給控制器​​。控制器看起來像:

export class MapIZSController 
{ 
    static $inject = ["$scope", "leafletData"]; 
    private m_scope: IMapIZSScope; 
    private m_leafletData; 

    constructor($scope: IMapIZSScope, leafletData) 
    { 
     // the first way I tried 
     $scope.init = function (type) { 
      console.log("type is: " + type); 
     }; 
     // the second way I tried 
     $scope.init = this.init; 
    } 

    public init = (init: any) => { 
     console.log("init is: " + init) 
    } 

我的問題是,我想獲得一個類型,但

  • 第一種方式,不會被調用
  • 第二了。

你能給我一些建議嗎?

+0

這個*可能*工作,但這不是'[ng-init']的預期用途(https://docs.angularjs.org/api/ng/directive/ngInit)。 「這個指令可能會被濫用,爲你的模板添加不必要的邏輯,只有少數'ngInit'正確的使用,例如爲'ngRepeat'的別名特殊屬性...'。 'ng-init'是一個指令,具有優先級,這意味着它可能不會按照您期望的順序執行,並且您可能依賴尚未提供的數據。 – Claies

回答

3

我想說你是在正確的軌道上。有a working plunker

這可能是有點簡化控制器:

namespace MyNamespace 
{ 
    export class MapIZSController 
    { 
    static $inject = ["$scope", "leafletData"]; 
    private m_scope: IMapIZSScope; 
    private m_leafletData; 

    private _type; 
    constructor($scope: IMapIZSScope, leafletData) 
    { 
     // // the first way I tried 
     // $scope.init = function (type) { 
     //  console.log("type is: " + type); 
     // }; 
     // // the second way I tried 
     // $scope.init = this.init; 
    } 

    public init = (type: any) => { 
     this._type = type 
     console.log("type is: " + this._type) 
    } 
    } 
} 

而這樣一來,我們可以調用初始化它:

<div class="col-md-9" 
    ng-controller="MapIZSController as ctrl" 
    ng-init="ctrl.init('IZS')"> 
</div> 

所以,我們使用controllerAs方法,並有機會獲得控制器通過ctrl. ...和那種方式呼叫ctrl.init()

檢查它here

+0

謝謝。但是如果我需要知道構造函數中的類型是什麼?這可能嗎? –

+1

一般來說,如果您需要將一些值傳遞給控制器​​(在創建過程中) - 使用原生方法 - 指令。在這裏你可以定義你的$ scope的屬性(或直接綁定到ctrl),甚至在構造函數中訪問它們(或者至少掛鉤一些$手錶直到它們被解析)。檢查這個問題與工作示例 - http://stackoverflow.com/q/32993497/1679310 –

+1

也在這裏http://stackoverflow.com/q/30482138/1679310;)希望這些提示將有助於... –

相關問題