0

I am developing a web application using AngularJS. I have a problem with the $scope object. My application is made up of many HTML pages and there is one where I use a multitude of different <form> (Which are enabled in cascade with ng-if), like that:

<form name="formOne" class="form-alignment">
   <div>Elements of form...</div>
   <div>Elements of form...</div>
</form>

<div ng-if="someMethod()>
   <form name="formTwo" class="form-alignment">
      <div>Elements of form...</div>
      <div>Elements of form...</div>
   </form>
</div>

<div ng-if="someOtherMethod()>
   <form name="formThree" class="form-alignment">
      <div>Elements of form...</div>
      <div>Elements of form...</div>
   </form>
</div>

In the controller I use the $scope object to immediately understand when these forms are valid or invalid through the $valid property, using watches... like that:

$scope.$watch(angular.bind(this, function () {
            return $scope.formOne.$valid;
        }), function (newValue, oldValue) {
            if($scope.formOne.$valid == true) {
                console.log("First form valid")
            } else {
                console.log("First form invalid")
            }
        });

Unfortunately I don't understand why the $scope object only detects the first form and not all the others (even if they are displayed on the web page!). For example, if I print in the console the $scope object, the result is:

enter image description here

As you can see, only formOne (and therefore its formOne.$valid, formOne.$invalid, etc) properties are detected in the object, but no formTwo and formThree! For example, if you wanted to use the property formOne.$valid in a watch made as before, I obtain the following error:

enter image description here

Although this property exists and it is also possible to see it directly in the template by doing {{formTwo.$valid}} for example!

How is this problem solved? and why does it happen?

1 Answer 1

1

This happens because ng-if creates a child scope. In order to fix this you could use ng-show instead or put the forms in an object.

// controller
$scope.forms = {};

// view
<form name="forms.formOne" class="form-alignment">
    <div>Elements of form...</div>
   <div>Elements of form...</div>
</form>

<div ng-if="someMethod()>
   <form name="forms.formTwo" class="form-alignment">
      <div>Elements of form...</div>
      <div>Elements of form...</div>
   </form>
</div>

<div ng-if="someOtherMethod()>
   <form name="forms.formThree" class="form-alignment">
      <div>Elements of form...</div>
      <div>Elements of form...</div>
   </form>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.