angularjs - 如何从 TypeScript Controller 中的表单引用属性和方法?

标签 angularjs typescript

我有一个简单的问题,我还没有找到答案。

在常规的 Angular JavaScript 中,如果我有这样一个表单的开头:

<form novalidate action="" class="signupForm" name="signup.form">
    <div class="row">
        <div class="col-md-12 ">
            <fieldset>
                <input type="text" name="fullName" placeholder="Full Name" ng-model="signup.fullName" required />{{signup.fullName}}
                <div ng-show="signup.form.$submitted || signup.form.$touched">
                    <span ng-show="signup.form.$error.required">Please enter your full name.</span>
                </div>
            </fieldset>
        </div>
    </div>

例如,使用 controllerAs,使用 SignupCtrl as signup 和 UI Router,我可以像这样在我的 Controller 中引用我的表单:

.controller(function() {
     this.form // shows me my form
 });

但是,在 TypeScript 中,this 指的是我的类及其自己的变量和方法,除非我弄错了。我如何在我的 TypeScript Controller 中引用表单或任何东西?现在范围如何绑定(bind)到 View ?

export class SignupCtrl implements ISignupCredentials {                     

        constructor(protected $http: ng.IHttpService, 
                    protected $q: ng.IQService,
                    protected $scope: IScope) {                                                

            console.log(this.form); // undefined because form doesn't exist in my controller class                                    
        }


    }

最佳答案

我们这样做:

function myDirective(): ng.IDirective
{
    return {
        restrict: "E",
        templateUrl: 'template.html',
        controller: 'MyController',
        scope:
        {
        },
        link: (scope, element, attrs, controller: MyController) =>
        {
            scope.vm = controller;
        }
    };
}

angular.module('mod').directive("mydirective", myDirective);

export class MyController
{
    public ImOnHTML: string = "helloWorld";

    static $inject = [];
    constructor()
    {

    }
}

angular.module('mod').controller('MyController', MyController);

然后在 template.html 中,所有 Controller 属性都将位于 vm.

所以: <input ng-model="vm.ImOnHTML"/>

关于angularjs - 如何从 TypeScript Controller 中的表单引用属性和方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551154/

相关文章:

javascript - 为什么 ng-repeat 中的函数会被调用多次?

angularjs - 为选择选项组提供样式

node.js - 如何以 Angular 4在帖子正文中发送数据

javascript - 如何创建一个 Observable<any[]>?

javascript - ionic 框架问题中的ui-router

javascript - 如何使用 Angular js 销毁每个 http 请求之前的响应?

javascript - 如何在 AngularJS 中公开公共(public)函数

typescript - 在 VS Code 中使用 Async/Await 调用 InputBox 的正确方法

typescript - 如何在 Typescript 1.7 中使用 CommonJS 模块正确生成 ES6 目标?

Angular 语言服务管道导致标识符未定义错误