0

I have a JSON where the version number corresponds to string which are manually inserted in the html. The JSON example:

  Object $$hashKey : "007"
  tenant : "A. Edition" 
  uri :"1101403" 
  version : "4"

In the html:

 <th ng-click="sortData('version')">
          Version
 </th>

<tr ng-repeat="t in tenants | orderBy:sortColumn:reverseSort" >
  <td>
    <span ng-if="t.version==1" >Business Edition</span>
    <span ng-if="t.version==2" >Non-business Edition</span>
    <span ng-if="t.version==3" >Bank Edition</span>
    .......
 </td>

Sort function:

$scope.sortData = function (column) {
    $scope.reverseSort = ($scope.sortColumn == column) ?!$scope.reverseSort: false;
    $scope.sortColumn = column;
}

I want to sort with the strings (Business Edition, Non-business Edition etc.) instead of t.version. How do I easily do that (new to angular)? Thanks for your help.

1

1 Answer 1

1

Basic principles of object oriented programming can be used here. You could turn your 'version' property into an object that has 'id' and 'value' properties:

//your tenants object
[
    {
        tenant: "A. Edition",
        uri: "1101403",
        version:
        {
            id: 1,
            value: "Business Edition"
        }
    },
    {
        tenant: "B. Edition",
        uri: "1101404",
        version:
        {
            id: 2,
            value: "Non-Business Edition"
        }
    },
    {
        tenant: "C. Edition",
        uri: "1101405",
        version:
        {
            id: 1,
            value: "Business Edition"
        }
    },
    {
        tenant: "D. Edition",
        uri: "1101406",
        version:
        {
            id: 3,
            value: "Bank Edition"
        }
    }
]

Nice thing is this simplifies your html too:

<tr ng-repeat="t in tenants | orderBy:sortColumn:reverseSort" >
  <td>
    <span>{{t.version.value}}</span>
 </td>

Then when you set your sort term:

$scope.sortColumn = 'version.id';
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. This is exactly what I want to do, but in this case I can't change the JSON.
@K_Sg, hmm in that case it could get messy. This is the cleanest way to do it that I know of. You CAN change the JSON if you just massage the data in your angular controller to format it like above. It won't come from the server this way, but you could loop through the data and format it this way. I'm not suggesting that's the best approach, but it's possible and not really that much code..
@ big_water, Yes, thanks a lot for explaining this to me. Let me try this way.
@K_Sg, glad it worked! Can you please accept the answer so others know the question is closed? Thanks!

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.