Javascript 检查 ng-if 语句中的字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44174845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:22:44  来源:igfitidea点击:

checking string value in ng-if statement

javascriptangularjsangular-ng-if

提问by bluePearl

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.

到目前为止,所有 div 都与正文中的文本一起出现,其中只有两个 div 应该显示它。

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

我的 ng-if 语句和字符串比较有什么问题吗?

回答by Jayant Patil

Here is the demo Jsfiddle

这是演示Jsfiddle

Js code

js代码

  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

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

希望这能解决您的问题

回答by bluePearl

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

我意识到在 angular 2 中, if 语句是:*ngIf而不是ng-if

回答by raviook

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>