Search code examples
javascriptangularjsng-showng-hide

Show and hide different contents with angularjs ng-show / ng-hide


I am new with angularjs and struggling to make some logic for Showing and hiding different Div's using ng-show and ng-hide based on different click.

PLUNKER

View 1:

<div ng-hide="section1">
  <select>
    <option>Select List 1</option>
    <option>Select List 2</option>
  </select>
</div>
<div ng-hide="section1">
  <ul>
    <li ng-repeat="name in names">{{name.item}}</li>
  </ul>
  <button type="button" ng-click="section1=!section1">Edit</button>
</div>

Initially it shows a Dropdown, some list Item and Edit button

Clicking on Edit button Everything hides and shows View 2

View 2:

<div ng-show="section1">
       <button type="button" ng-click="section2=!section2">+ Create New Item</button>
    </div>
    <div ng-show="section1">
      <ul>
        <li ng-repeat="name in names">
          <input type="text" ng-model="name.item">
        </li>
      </ul>
      <button type="button" ng-click="section1=!section1">Save</button>
    </div>

On view 2 There is a button "Create New item" , List of Input fields with same value of view 1's list items and a save button. This view 2 is basically edit mode of view 1.

Upto now works fine.

Problem: If I click "+Create new item", "View 2" Should Hide and "View 3" should Open.

View 3 Contains some blank input list and "Save button".Clicking on "save button" Hide "View 3" and again open "View 1".

View 3

<div ng-show="section2">
      <ul>
        <li ng-repeat="name in names">
          <input type="text">
        </li>
      </ul>
      <button type="button" ng-click="section2=!section2">Save New List</button>
    </div>

I am struggling to manage 3 different view based on different button click with ng-show and Hide. It's not showing and hiding properly from clicking "+create new button".

Is this possible to make it work perfectly with ng-show & ng-hide only ? Is there any better way to handle ?

Any help will be appreciated.


Solution

  • A better way to handle what you're trying to do is to have a variable that holds the index of the current section. Then, you could use something like ng-show="currentSection === 1" which I think would be a little more straight forward.

    Then your click action could look more like ng-click="currentSection = 1". That will show all elements with ng-show="currentSection === 1".

    Does that help any?