Div won't hide when button in controller AngularJS

66 Views Asked by At

I'm new to AngularJS and am trying to hide a div when a button is clicked. What I'm doing works fine until I put the button in the div I'm trying to hide (the button is using a different controller). The button works as expected when taken out of the controller so I assume it's an issue with scope. Any help would be appreciated.

<form action="" name="signUpForm" class="heroForm" >
      <div ng-hide="signUpB">
            <span id="signUpFormA">
                  <input required type="email" /> 
                  <input required type="password"/>
                  <span ng-controller="checkEmailCtrl">
                        <input type="button" ng-click="signUpB=true">
                  </span>
            </span>
      </div>
      <div ng-show="signUpB">
            <span id="signUpFormB">
                  <input required type="text">
                  <input required type="text">
                  <input type="submit">
            <span>
      </div>
</form>
2

There are 2 best solutions below

0
On BEST ANSWER

Yes, you are setting signUpB=true on the scope of checkEmailCtrl. You can do something like this:

<form action="" name="signUpForm" class="heroForm" ng-init="signUpB={value:false}">
      <div ng-hide="signUpB.value">
            <span id="signUpFormA">
                  <input required type="email" /> 
                  <input required type="password"/>
                  <span ng-controller="checkEmailCtrl">
                        <input type="button" ng-click="signUpB.value=true">
                  </span>
            </span>
      </div>
      <div ng-show="signUpB.value">
            <span id="signUpFormB">
                  <input required type="text">
                  <input required type="text">
                  <input type="submit">
            <span>
      </div>
</form>

By wrapping the signUpB in an object, the signUpB.value=true statement will look up the signUpB object in the outer scope, and set it's value property to true, no modification will be made on checkEmailCtrl's scope.

0
On

ng-controller creates its own scope. So, within ng-click="signUpB=true", you are modifying the signUpB in this new scope.

You can fix this by using a object to hold the state of signUpB. Basically, replace all signUpB occurrences with state.signUpB. And, define state object in your outer controller's scope.

$scope.state = {signUpB: false // defaults to false}

Even better approach would be to use controllerAs syntax. Let's say your outer controller is OuterController. You define it as

ng-controller="OuterController as outerCtrl"

and,

replace all occurrences of signUpB with outerCtrl.signUpB to ensure you are using/modifying outerCtrl's model.