Search code examples
javascripthtmlangularjsformsangularjs-ng-form

Getting form's name within Angular (this.form.name)


There is a simple form

<ng-form name="foo">
    <button />
</ng-form>

Click on the button should alert the form name foo.

Is there an angular-way to do that?

EDIT: Tell me my parent's name is a possible solution.


Solution

  • Assuming that the button has the form as it's direct parent, you can utilize the $event property on ng-click to traverse the DOM and locate the parent form element. This uses angular.element(someElement).parent().

    $scope.showFormName = function($event) {
      $scope.formName = angular.element($event.target).parent()[0].name;
    };
    
    <button ng-click="showFormName($event)">Show Form Name</button>
    

    http://plnkr.co/edit/yDPc76rqUHpOcL2aGeIU?p=preview

    If the button is not a direct descendant of the form element, or is not within the form itself, then more advanced DOM traversal may be required, most likely through JQuery, since this isn't part of the design goals of the Angular framework.