Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs components getting a form inside template

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? 
    }
 });
like image 544
Luna Avatar asked Mar 17 '16 15:03

Luna


1 Answers

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.

like image 176
Dave Avatar answered Oct 19 '22 03:10

Dave