Mr. Smith Mr. Smith - 1 year ago 105
AngularJS Question

angularjs components getting a form inside template

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


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

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

.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?

Answer Source

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'>

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download