如果value ==“ string”,否则如何显示ng-repeat中的值,否则不显示

时间:2019-04-18 12:58:11

标签: javascript angularjs mean-stack

我正在尝试用字符串“ Yup”和“”替换表中的数据:如果字符串等于“ yes”,则显示“ Yup”,否则不显示,对不起,我是新手,我看到了一些解决方案,但我尝试了一下,但没有用:{{ person.value ? "Yup":" "}} ..请提供任何帮助

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.register = {
      value: [
        {value:"Yes"},{value:"no"},{value:"yes"},
        {value:"No"},{value:"no"}
      ],
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<table id="example" width="100%">
    <thead>
       <tr align="center">
         <th>Value</th>
         <th>Replace</th>
       </tr>
    </thead>			
    <tbody>
       <tr ng-repeat="person in register.value">
         <td align="center">{{ person.value }}</td>
         <td align="center">{{ person.value ? "Yup":" "}}</td>
       </tr>
    </tbody>
</table> 
</div>

2 个答案:

答案 0 :(得分:2)

如果您无法更改值,则可以在值上调用toLowerCase()以确保其为小写字母,然后将其与"yes"进行比较

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.register = {
      value: [
        {value:"Yes"},{value:"no"},{value:"yes"},
        {value:"No"},{value:"no"}
      ],
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<table id="example" width="100%">
    <thead>
       <tr align="center">
         <th>Value</th>
         <th>Replace</th>
       </tr>
    </thead>			
    <tbody>
       <tr ng-repeat="person in register.value">
         <td align="center">{{ person.value }}</td>
         <td align="center">{{ person.value.toLowerCase() == "yes" ? "Yup":" "}}</td>
       </tr>
    </tbody>
</table> 
</div>

代码不起作用的原因是,当您使用三进制(? :)时,它将值转换为真实值,并且非空字符串将始终为true,因此每个值均为true,并将始终成为"Yup"

答案 1 :(得分:0)

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.register = {
      value: [
        {value:"Yes"},{value:"no"},{value:"yes"},
        {value:"No"},{value:"no"}
      ],
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<table id="example" width="100%">
    <thead>
       <tr align="center">
         <th>Value</th>
         <th>Replace</th>
       </tr>
    </thead>            
    <tbody>
       <tr ng-repeat="person in register.value">
         <td align="center">{{ person.value }}</td>
         <td align="center">{{ person.value.toLowerCase() == "yes" ? "Yup":" "}}</td>
       </tr>
    </tbody>
</table> 
</div>