angularjs components getting a form inside templat

2019-03-25 11:31发布

问题:

so I have a component with a template containing a form.

mycomponent.html:

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

How can I access myForm inside the component controller? Currently I'm injecting $scope to get it from that. Or is that the only way to get the form?

Edit: Added some code to better illustrate in 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? 
    }
 });

回答1:

The name attribute of a form is what angular uses to decide what to bind to. So, if you're using the controllerAs syntax, you have to use that in the form name:

  <body ng-controller="MainCtrl as vm">
    <form name='vm.myForm'>
    </form>
  </body>

This will allow you to refer to it in your controller without using $scope, but only after the controller has been successfully created:

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

    var vm = this;

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

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

Here is a working plunk.



回答2:

Use the name syntax but also a components postLink lifecycle hook, that function is called once a template and controller have been connected see https://docs.angularjs.org/guide/component