angularjs 个组件在模板中获取表单

angularjs components getting a form inside template

所以我有一个组件,其模板包含一个表单。

mycomponent.html:

<div>
    <form name="myForm"> 
        <!-- more html code -->
    </form>
</div>

如何访问组件控制器中的 myForm? 目前我正在注入 $scope 以从中获取它。 或者这是获取表格的唯一方法?

编辑:添加了一些代码以更好地说明 javascript

angular.module('example')
.component('myComponent', {

    templateUrl: 'mycomponent.html',
    controller: function($scope) {
         $scope.myForm // This works
         this.myForm // undefined, can I access it through the component scope instead of $scope somehow? 
    }
 });

表单的 name 属性是 angular 用来决定绑定到什么的。因此,如果您使用 controllerAs 语法,则必须以 name:

的形式使用它
  <body ng-controller="MainCtrl as vm">
    <form name='vm.myForm'>
    </form>
  </body>

这将允许您在不使用 $scope 的情况下在您的控制器中引用它,但仅在成功创建控制器之后:

app.controller('MainCtrl', function($scope, $timeout) {

    var vm = this;

    console.log(vm.myForm);  // undefined

    $timeout(function() {
        console.log(vm.myForm);  // FormController object
    }, 100);
});

这是一个有效的 plunk

使用名称语法以及组件 postLink 生命周期挂钩,一旦连接模板和控制器就会调用该函数,请参阅 https://docs.angularjs.org/guide/component