angularjs $scope form undefined

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.

Advertisements

2 comments

  1. balu · March 8, 2016

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

    • LEON · March 8, 2016

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s