Anusha
Anusha

Reputation: 346

ng-if and ng-show in my Ionic application, neither works

The html code goes something like this:

<div ng-if="name=='John'">
<div class="item item-avatar"> <img ng-src="john.jpg"></div>
</div>
<div ng-if="name=='Margaret'"
<div class="item item-avatar"> <img ng-src="margaret.jpg"></div>
</div>

Instead of ng-if, I've tried using ng-show as well. Neither worked. Both John as well as Margaret showed on the page no matter which I used. I tried with ng-switch also.

The variable 'name' I initialized earlier on the same HTML file as:

<a class="item item-avatar item-icon-right" ng-init="name = 'John'" href = "#/Page3"></a>

Clicking on the above line leads to Page3 where I need to display either John or Margaret depending on the value of 'name'.

Is the syntax wrong or something, because that could be very well possible. I'm new to Ionic and AngularJS.

Upvotes: 2

Views: 26358

Answers (3)

Michael
Michael

Reputation: 3104

I fixed you plunker - now it should be working.

Bug #1: ng-init is for initialization not to set values at runtime -> use ng-click instead

Bug #2: You use the same controller for all pages but for each page a new controller will be initialized, which resets the 'name' property

I implemented a setName function to set the name in the rootscope and to go to page3. In a correct implementation you should pass the name as a $stateparam to the new state/page. But for that please have a look at the ui-router documentation.

  $scope.setName = function(name) {
    console.log(name);
    $rootScope.name = name;
    $state.go('Page3');
  };

Upvotes: 0

Michael
Michael

Reputation: 3104

Are you sure you started Angular? Did you set the ng-app directive? It would help if you could provide a working example if you have other problems.

angular.module('app', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-init="name = 'John'">
  <button type="button" ng-click="name='John'">John</button>
  <button type="button" ng-click="name='Margaret'">Margaret</button>

  <div ng-if="name=='John'">
      This is John
  </div>
  <div ng-if="name=='Margaret'">
    This is Margaret
  </div>
</div>

Upvotes: 1

bonchenko
bonchenko

Reputation: 577

Try this:

<div ng-show="name=='John'" ng-init="name = 'John'">
  <div class="item item-avatar"> John</div>
</div>
<div ng-show="name=='Margaret'"
  <div class="item item-avatar"> Margaret</div>
</div>  

Works for me. I just change ng-if to ng-show - which will shows div content when true and hide it otherwise. I also use ng-init inside a div.

Upvotes: 1

Related Questions