Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-if not working in a Form

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>
like image 885
Quai Avatar asked Dec 22 '15 13:12

Quai


2 Answers

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

like image 84
Kasper Lewau Avatar answered Oct 01 '22 18:10

Kasper Lewau


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;
like image 43
RIYAJ KHAN Avatar answered Oct 01 '22 18:10

RIYAJ KHAN