TonyTakeshi
TonyTakeshi

Reputation: 5929

AngularJS from $scope get form controller programmatically

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.

Upvotes: 2

Views: 1632

Answers (2)

Jim Schubert
Jim Schubert

Reputation: 20357

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
        }
      };
    });

Upvotes: 5

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.

Upvotes: 1

Related Questions