1

Using below JSON object need to show key.

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

Below are the conditions: 1. If got fieldName, fieldLabel, and fieldKey then need to show fieldLabel 2. If only received fieldLabel and fieldKey then need to show fieldLabel 3. If only received fieldKey and fieldName then need to show fieldName

1
  • function valueToBeDisplay(displayProp, objKey, field, htmlStr) { angular.forEach(field, function (value, key) { if (field.fieldLabel ? field.fieldLabel : field.fieldName) { htmlStr += formatLabel(field[key]); //formatLabel is other function } }); return htmlStr; } Commented Jan 4, 2018 at 5:01

1 Answer 1

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

^^ should work assuming you're talking about binding that data into the view (using ternary operator, if object.fieldLabel, then print 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>

Sign up to request clarification or add additional context in comments.

3 Comments

I tried your solution but its shown all object instead of showing only fieldLabel. Please find below my code: angular.forEach(field, function (value, key) { if (field.fieldLabel ? field.fieldLabel : field.fieldName) { htmlStr += formatLabel(field[key]); } });
@rahulPawar yeah so the ? : syntax is called "ternary operator" it just means if the thing before the ? then do the thing after the question mark else do the thing after the colon, so it's just short-hand of an if-then-else, I used it to keep the syntax concise in the view code. If you need to see how to do the conditions in the original question in JS not in the view binding let me know and can add that answer as well.
@ shaunhusain, Thanks for above solution... after made some changes now its working for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.