checking string value in ng-if statement

bluePearl picture bluePearl · May 25, 2017 · Viewed 44.9k times · Source

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?

Answer

Jayant Patil picture Jayant Patil · May 25, 2017

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