如何使用angularjs在条件基础上显示特定的JSON对象键

时间:2018-01-04 02:36:44

标签: angularjs json

使用下面的JSON对象需要显示键。

{
   'fieldLabel': 'LABEL',
   'fieldName': 'TEST',
   'fieldKey': 'TEST2'
}

以下是条件: 1.如果得到fieldName,fieldLabel和fieldKey则需要显示fieldLabel 2.如果只收到fieldLabel和fieldKey则需要显示fieldLabel 3.如果只接收到fieldKey和fieldName,则需要显示fieldName

1 个答案:

答案 0 :(得分:1)

{{object.fieldLabel?object.fieldLabel:object.fieldName}}

^^应该可以正常工作,假设您正在讨论将数据绑定到视图中(使用三元运算符,如果是object.fieldLabel,则打印object.fieldLabel else print object.fieldName)。



angular.module('myapp', [])
  .controller('MyCtrl', function($scope){
    $scope.objects = [
      {fieldLabel: 'I got a label'},
      {fieldName: 'I only have a name :('}
    ] 
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>
<div ng-app="myapp" ng-controller="MyCtrl">
  <div ng-repeat="object in objects">
  {{object.fieldLabel?object.fieldLabel:object.fieldName}}
  </div>
</div>
&#13;
&#13;
&#13;