【问题标题】:Angular+TypeScript - pass parameter from view to controllerAngular+TypeScript - 将参数从视图传递到控制器
【发布时间】:2015-10-08 00:25:13
【问题描述】:

我正在使用带有 TypeScript 的 AngularJS,现在我需要将参数从视图传递到控制器。这就是我尝试的方式(通过 ng-init):

<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)
    } 

我的问题是我想获得一个类型,但是

  • 第一种方式永远不会被调用并且
  • 第二个也是。

你能给我一些建议吗?

【问题讨论】:

  • 可能有效,但这不是the intended use for ng-init。 “可以滥用此指令在模板中添加不必要的逻辑量。ngInit 只有少数适​​当的用途,例如为ngRepeat 的特殊属性设置别名...”。 ng-init 是一个指令,具有优先级,这意味着它可能不会按照您期望的顺序执行,并且您可能依赖于尚未提供的数据。

标签: angularjs angularjs-scope typescript


【解决方案1】:

我会说你在正确的轨道上。有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

【讨论】:

  • 谢谢。但是如果我需要知道它在构造函数中已经是什么类型呢?这可能吗?
  • 一般来说,如果您需要将一些值传递给您的控制器(在创建期间) - 使用本机角度方法 - 指令。在这里,您可以定义 $scope 的属性(或直接将其绑定到 ctrl。)并在构造函数中访问它们(或至少挂钩一些 $watches 直到它们被解析)。通过工作示例检查此问答 - stackoverflow.com/q/32993497/1679310
  • 还有stackoverflow.com/q/30482138/1679310 ;) 希望这些提示会有所帮助...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
相关资源
最近更新 更多