How can I check an ng-included form's validity from the parent scope?

后端 未结 2 1831
滥情空心
滥情空心 2020-12-25 12:06

I have a subform that is shared among multiple views in my app. In one view, this subform is displayed alone with a back/continue button at the bottom that leads the user to

相关标签:
2条回答
  • 2020-12-25 12:30

    If it's a sub-form you can just move the form-tag from the sub-form and into the main-form: updated JSFiddle

    You could also nest your forms using the ngForm-directive:

    In angular forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However browsers do not allow nesting of elements, for this reason angular provides ngForm alias which behaves identical to but allows form nesting.

    The result is a bit messy imo. I'd rather create a 'myForm'-directive with a new scope to avoid using $parent - something like:

    myApp.directive('myForm',function(){
        return{ 
            restrict:'E',
            scope:{model:'='},
            templateUrl:'/form.html',
            replace:true
        }
    });
    

    - see this JSFiddle example

    0 讨论(0)
  • 2020-12-25 12:37

    The child scope created when you use ng-include is hiding the form functions from the parent.

    In addition to using a directive, you can also add an object in the parent, but it's important to set the name of the form to an object with a property like so:

    <form name="myFormHolder.myForm">
    

    and in the parent controller

    $scope.myFormHolder = {};
    

    then the following should work:

    $scope.myFormHolder.myForm.$pristine
    

    This way when the form is evaluated, myForm.$valid will get set on the parent. I believe I asked this same question: Why form undefined inside ng-include when checking $pristine or $setDirty()?

    0 讨论(0)
提交回复
热议问题