0

I have an object I want to put in a table. the object seems like: {"text":"111","order":["1","2","3","4","5"]} there may be array as well as simple strings. So how can I put this object in a table if I want the table to look like this:

property   value
text       111
order      1,2,3,4,5

My table shows in the value column ["1","2","3","4","5"] instead of 1,2,3,4,5.

Here is what I wrote:

<tr data-ng-repeat="(key,val) in object">
    <td>
        {{ key }}
    </td>   
    <td>
        {{val}}
    </td>        
</tr>

I also tried with ng-swtich but it didn't work.

3
  • 1
    You could check if the val is an Array and join them.. Commented Jan 12, 2015 at 17:23
  • Can you post more of your relevant code? At least the controller for your app? Commented Jan 12, 2015 at 17:23
  • @Karthik how can I check if its an array and join them? Commented Jan 12, 2015 at 17:27

2 Answers 2

1

Here is a sample which checks if the value is an Array and joins them as a string.

Html:

 <tr data-ng-repeat="(key,val) in object">
    <td>
        {{ key }}
    </td>   
    <td>
        {{val | isArray}}
    </td>        
  </tr>

Controller:

app.controller('MainCtrl', function($scope) {
  $scope.object = {"text":"111","order":["1","2","3","4","5"]};
});

app.filter("isArray", function() {
      return function(input) {
        var isArray = angular.isArray(input);
        if(isArray)
          return input.join();
        return input;
      };
});

Working code here

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

Comments

1

Is this what you were after?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="app" ng-controller="MyTableController">
  <tr data-ng-repeat="(key,val) in data">
    <td>
      {{ key }}
    </td>

    <td >
      {{ val | join: ', ' }}
    </td>        
  </tr>
</table>

<script>
angular.module('app', [])
  // Filter that joins the input with the supplied separator
  .filter('join', function () {
    return function (value, separator) {
      if (typeof value.join === 'function') {
        return value.join(separator);
      } else {
        return value;
      }
    }
  })
  .controller('MyTableController', function ($scope) {
    $scope.data = {"text":"111","order":["1","2","3","4","5"] };
  });
</script>

1 Comment

Thank you for your answer, it is what i'm looking for. unfortunately I cant accept 2 answers

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.