angularjs $scope form undefined

on

Was developing some form with angular, things work perfect until I add a angular-ui bootstrap tab to enclose 2 different form in each tab.

when i try to access the form with $scope.formName, the formName is undefined.

It turns out that the angularUI tab directive uses transclude which will create a child scope to the parent which here is the controller $scope as the sibling of the directive scope. Then the formName can only be access by the new child scope.

One solution is define a var in the controller scope like $scope.forms = {};

Then for the form name in the transclude directive, we use forms.formName1. This way we could still access it from our controller by just call $scope.forms.formName1.

This works because the inheritance mechanism in JS is prototype chain. So when child scope tries to create the forms.formName1, it first tries to find the forms object in its own scope which definitely does not have it since it is created on the fly. Then it will try to find it from the parent(up to the prototype chain) and since we have it defined in the controller scope, it uses this ‘forms’ object we created to define the variable formName1. As a result we could still use it in the controller like $scope.forms.formName1.$valild to do our stuff.

2 Comments Add yours

  1. balu says:

    hi its again shows as undefined error, cant able to validate the form

    1. LEON says:

      what context are you in? Did you put your form into another directive which creates a new scope for its containing content?

Leave a comment