问题描述:

I try to hide my form after it has been 'submitted'. I want to do it with ng-if. Clicking on the button 'See' displays the form on and off, but it does not work on the button 'Add'. What is the reason for that?

I have 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>

网友答案:

Please, don't use $parent!

Use proper prototypal inheritance.

The reason it doesn't work is because you are creating a new scope through the usage of ngIf.

It does not create an isolate scope so you don't have to worry about that.


When you pass a primitive, Javascript will "shadow" that value on the prototype of the new scope.

As such, it is no longer a direct reference to the value in your parent scope.

How do you get around that?

add a dot

That roughly translates into; use an object and bind to a property of that object. objects don't get shadowed as they are not a primitive. you get to keep the reference and it just works™.

jsfiddle

网友答案:

Every directive in angularjs create different level of scope.So,there is different level of scope, one at form tag and one at button inside the form which create parent and child relationship between form and button inside it.As add is,primitive variable,its changes in child is not reflected in parent scope.

So,either use $parent service or define thet add variable in following way.

$scope.objHidShow = {};
$scope.objHidShow.add= false;
网友答案:

i would do it by calling a controller function:

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

what i did is to define that function and i made your controller working for the complete form.

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

updated your fiddle. merry christmas ;)

网友答案:

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

相关阅读:
Top