10

I would like to check the value of the property of an object and would like to check the data of string to compare.

<div ng-if="results.dataType === 'textTable'"> 
     This text belongs in a table. 
</div>

So far all the divs appear with the text in the body where only two divs should display it.

Is there anything wrong with my ng-if statement and string comparison?

Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
bluePearl
  • 1,237
  • 4
  • 24
  • 42
  • If this is AngularJS (sometimes called "Angular 1"), then the correct tag is "angularjs". –  May 25 '17 at 07:53
  • The way I see it from your code is that you have a object with a value which you compare it with a string. So supposing that you are wrapping the ng-if in a ng-for, to generate multiple divs you should have an array with result values specific for each new created div to actually work that ng-if – sTx May 25 '17 at 14:13
  • @torazaburo this is in angular 2 – bluePearl May 25 '17 at 16:08
  • @sTx yes my ng-if is wrapped in a ngFor `results` is the returned items array that contains the data but my if statements doesn't seem to work but not sure why. – bluePearl May 25 '17 at 16:10

3 Answers3

6

Here is the demo Jsfiddle

Js code

  var app = angular.module('myApp', []);

  app.controller('ctrl', function($scope) {
    $scope.results = {
      dataType: 'textTable'
    };
    $scope.flag = true;

    // for testing purpose

    $scope.toggle = function() {
      if ($scope.flag) {
        $scope.results = {
          dataType: 'textTable'
        };
        $scope.flag = !$scope.flag;
      } else {
        $scope.results = {
          dataType: 'textTableNot'
        };
        $scope.flag = !$scope.flag;
      }

    }
  });

HTML

  <div ng-app='myApp'>

    <div ng-controller='ctrl'>
      <div ng-if='results.dataType === "textTable"'> This text belongs in a table.</div>
      {{results.dataType}}
      <button ng-click='toggle()'>
        Toggle
      </button>
    </div>
  </div>

Hope this will resolve your problem

Jayant Patil
  • 1,537
  • 2
  • 11
  • 18
  • I tried this syntax but in the view i would get `{{results.dataType}}` displayed even if it doesn't equal `textTable` - i am doing this in angular2 – bluePearl May 25 '17 at 16:11
1

I realized that in angular 2 the if statement is: *ngIf and not ng-if.

bluePearl
  • 1,237
  • 4
  • 24
  • 42
1

Hope this will resolve your problem.

<div>
<input type="hidden" ng-model="myVar" ng-init="myVar = 'stringformat'">
<div ng-if="myVar =='stringformat'">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
</div>
</div>
raviook
  • 99
  • 1
  • 5