2

Is there anyway I could access form controller from scope without knowing what what user define for form name.

Normally, we would access the form controller this way:

$form['register_form']

However, I am looking for way that can access to the form controller without knowing the form name. Example:

$form[$scope.form_name]

I assume there's reference to form name or form controller from $scope itself.

2 Answers 2

5

You can access the form using

angular.element(el).inheritedData('$formController');

This will get a reference to the element's parent form.

I've created a plunker example here. However, I wouldn't do this within a controller as I have done in the example. I'd put whatever logic you require a parent form for into a directive. Something like this:

.directive('myDirective', function() {
      return {
        require: '^form',
        restrict: 'A',
        controller: ['$scope', function($scope){
           $scope.$watch('form', function(val){
               // some controller logic
           });
        }],
        link: function(scope, element, attrs, frm) {
          scope.form = frm;
          // your other logic
        }
      };
    });
Sign up to request clarification or add additional context in comments.

Comments

1

If form isn't in $scope, you can put it there yourself. For example, it's possible with new directive named form, since AngularJS allows multiple directives of the same name.

Here's an extremely naive version of it:

.directive("form", function () {
  function link (scope, el, attr, ctrl) {
    scope.forms = scope.forms || [];
    if (scope.forms.indexOf(ctrl) === -1) {
      scope.forms.push(ctrl);
    } 
  }
  return {
    restrict: "E",
    link: link,
    require: "form"
  }
})

What I've done:

  1. Created new directive that will initialize on form elements.
  2. Required original form directive controller.
  3. Exposed it through scope.forms colletions.

JSBin.

2 Comments

Your solution excludes angular's support for nested forms. jsbin.com/rahomeve/2/edit
I didn't claim it does. For nested forms, you'll need similar directive for ngForm.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.