Search code examples
angularjsdatatablesangularjs-orderby

angularjs order by to object with space


I've a list of users that contains object with spaces like this;

'User Name, First Name, Last Name, Phone #, User Image'

while binding this list to datatable, I'm doing this to achieve my data

<tr ng-repeat="user in lstUsers | orderBy : ['User Name']>

   <td> <img ngf-thumbnail="user['User Image']" alt="" id="imgUserImage{{$index}}" /></td>
   <td>{{ user['User Name'] }}</td>
   <td>{{ user['First Name'] }}</td>
   <td>{{ user['Last Name'] }}</td>
   <td>{{ user['Phone #'] }}</td>                        
</tr>

it works perfectly fine except the order by, it gives error if I use it in this way orderBy : ['User Name']

Error: [$parse:syntax] Syntax Error: Token 'Name' is an unexpected token at column 6 of the expression [User Name] starting at [Name].

and if I use orderBy : '[User Name]' , it throws this error;

Error: [$parse:syntax] Syntax Error: Token 'Name' is unexpected, expecting []] at column 7 of the expression [[User Name]] starting at [Name]].

and if I use orderBy : 'User Name' , it throws this error;

Error: [$parse:syntax] Syntax Error: Token 'Name' is an unexpected token at column 6 of the expression [User Name] starting at [Name].

and if I use it without space like this orderBy : 'UserName' , it doesn't give any error but not apply any order to table.

What should I do to apply order on table? Any kind of help will be appreciated.


Solution

  • You can just surround a field name with UTF8 code for quotation mark:

    HTML

    <tr ng-repeat="user in lstUsers  | orderBy:'\u0022User Name\u0022'">
    

    DEMO

    angular.module("myApp",[]).controller("myController",function($scope){
      
    $scope.lstUsers  = [
    {"User Name": 'SACHIN', age: 12},
    {"User Name": 'AJMAL', age: 14},
    {"User Name": 'SMITH', age: 15},
    {"User Name": 'RICHARD', age: 16},
    {"User Name": 'OSCAR', age: 32}
    ];
    });
    <html ng-app="myApp">
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        </head>
    <body ng-controller="myController">
      
    <div ng-repeat="user in lstUsers | orderBy:'\u0022User Name\u0022' ">
       <h1>{{user['User Name']}}</h1>
       <h1>{{user.age}}</h1>
      </div>
     </body>
    
      </html>