AngularJs can't access form object in controller ($scope)

后端 未结 7 1420
臣服心动
臣服心动 2020-12-07 12:25

I am using bootstrap-ui more specifically modal windows. And I have a form in a modal, what I want is to instantiate form validation object. So basically I am doing this:

7条回答
  •  孤街浪徒
    2020-12-07 12:58

    Look at the source code of the 'modal' of angular ui bootstrap, you will see the directive has

    transclude: true
    

    This means the modal window will create a new child scope whose parent here is the controller $scope, as the sibling of the directive scope. Then the 'form' can only be access by the newly created child scope.

    One solution is define a var in the controller scope like

    $scope.forms = {};
    

    Then for the form name, we use something like 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. 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 here 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 our controller to do our stuff like:

    if($scope.forms.formName1.$valid){
          //if form is valid
    }
    

    More about transclusion, look at the below Misco's video from 45 min. (this is probably the most accurate explanation of what transcluded scopes are that I've ever found !!!)

    www.youtube.com/watch?v=WqmeI5fZcho

提交回复
热议问题