AngularJS ng - if not working on form

I try to hide my form after it has been submitted. I want to do this with ng-if. Clicking on the "View" button displays the form on. And off. But it does not work on the "Add" button. What is the reason for this?

I created a JSFiddle. Link to JSFiddle .

My form:

<form name="userAddForm" ng-submit="something()" class="form-horizontal" role="form"> <div class="form-group"> <label class="col-md-2 control-label">Username</label> <div class="col-md-3"> <input name="username" ng-model="user.username" class="form-control" ng-required="true" placeholder="Username" type="text" /> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Password</label> <div class="col-md-3"> <input name="password" ng-model="user.password" class="form-control" placeholder="Password" type="password" ng-required="true" /> </div> </div> <button ng-disabled="userAddForm.$invalid" type="submit" ng-click="add=!add" class="btn btn-success"> <span class="glyphicon glyphicon-ok"></span> Add </button> </form> </div> 
+5
source share
4 answers

Please do not use $ parent!

Use the correct prototype inheritance.

The reason it doesn't work is because you are creating a new area using ngIf .

It does not create a selection area, so you do not need to worry about it.


When you pass primitive , Javascript will "obscure" this value on the prototype of the new scope.

Thus, it is no longer a direct reference to a value in your parent area.

How do you get around this?

add point

This is roughly equivalent; use an object and bind to the property of this object. objects do not get shadows because they are not primitive. you can save the link and it just works ™.

jsfiddle

+3
source

Each directive in angularjs creates a different level of scope. Thus, there is a different level of scope, one in the form tag and one on the button inside the form, which create the parent and child links between the form and the button inside it. As add is a primitive variable, its changes in the child file are not reflected in the parent area.

So, use the $parent service or define the thet add variable as follows.

 $scope.objHidShow = {}; $scope.objHidShow.add= false; 
+3
source

I would do this by calling the controller function:

 $scope.something = function() { $scope.shown = !$scope.shown; } 

what I did was define this function and I made your controller work for the full form.

https://jsfiddle.net/udc2rjrn/2/

updated his violin. merry christmas;)

+2
source

The ng-if directive creates a new scope, so you need to use $parent :

 <button ng-disabled="userAddForm.$invalid" type="button" ng-click="$parent.add=!$parent.add" class="btn btn-success"> 

Updated JSFiddle

+1
source

Source: https://habr.com/ru/post/1238954/


All Articles