Can I access a form in the controller?

Vincent picture Vincent · Oct 24, 2013 · Viewed 172.6k times · Source

I'm currently using the following.

$scope.$$childHead.customerForm[firstName], so that:

<form name="customerForm">
  <input type="text" name="firstName" 
         ng-model="data.customer.firstName" 
         tabindex="1"  
         ng-disabled="!data.editable" 
         validationcustomer />
</form>

But this only works in Chrome. Now I tried the following:

$scope.editCustomerForm[firstName], so that:

<form name="customerForm" ng-model="editCustomerForm">
  <input type="text" name="firstName" 
         ng-model="data.customer.firstName" tabindex="1"  
         ng-disabled="!data.editable" 
         validationcustomer />
</form>

Which doesn't work. Note my form is inside a Foundation Tab. How can I access firstName?

EDIT: It looks like the form isn't added to the scope when it's inside a Foundation Tab.

Anyone has got a solution for this?

Answer

slopapa picture slopapa · Nov 25, 2014

Though alluded to in other comments I thought I'd spell it out a bit for those using the "Controller As" syntax:

<div ng-controller="MyController as ctrl">

<form name="ctrl.myForm">
    ...inputs
    Dirty? {{ctrl.myForm.$dirty}}

    <button ng-click="ctrl.saveChanges()">Save</button>
</form>

</div>

Then you can access the FormController in your code like:

function MyController () {
    var vm = this;
    vm.saveChanges = saveChanges;

    function saveChanges() {

       if(vm.myForm.$valid) { 
            // Save to db or whatever.
            vm.myForm.$setPristine();
       }
}