2015-10-07 91 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;)希望这些提示将有助于... –

相关问题