daniel-nagy / md-data-table

Material Design Data Table for Angular Material
MIT License
1.9k stars 519 forks source link

Dynamically assign md-numeric #595

Closed preraksola closed 7 years ago

preraksola commented 7 years ago

In my angular app, I want to assign the md-numeric directive to header based on a condition. This is the code that I have currently:

Controller:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {

  $scope.headers = [{
    title: 'Name Of X',
    v: 'name',
    t: 'string'
  }, {
    title: 'Value of X',
    v: 'value',
    t: 'int'
  }];

  $scope.testData = [{
    id: '1',
    name: 'TOTO',
    value: 1.34
  }, {
    id: '2',
    name: 'TOTO_1',
    value: 1.54
  }];
});

HTML:

<div ng-controller="MyCtrl">
  <table md-table>
    <thead>
      <tr md-row>
        <div>
          <th ng-repeat="header in headers" header.t=='int' ? md-numeric : ''>
            <span>{{header.title}}</span>
          </th>
        </div>
      </tr>
    </thead>
    <tbody md-body>
      <tr md-row ng-repeat="x in testData" id="{{x.id}}">
        <td ng-repeat="header in headers" md-cell>
          {{header.t == 'int' ? (x[header.v]|number: 2) : (x[header.v])}}
        </td>
      </tr>
    </tbody>
  </table>
</div>

Here as you can see, I want to assign the directive md-numeric only to those headers, whose type is int. But with the existing code, the directive is applied to every header. Here's a jsFiddle in which the header should get an orange background if the directive is present.

So how can I evaluate the condition for setting the directive?

preraksola commented 7 years ago

I just found in the documentation that you can assign an expression to the md-numeric directive. If the expression returns true, the directive will be applied. So I was able to achieve what I wanted using the below code:

<div ng-controller="MyCtrl">
  <table md-table>
    <thead>
      <tr md-row>
        <div>
          <th ng-repeat="header in headers" md-numeric = " header.t == 'int' "'>
            <span>{{header.title}}</span>
          </th>
        </div>
      </tr>
    </thead>
    <tbody md-body>
      <tr md-row ng-repeat="x in testData" id="{{x.id}}">
        <td ng-repeat="header in headers" md-cell>
          {{header.t == 'int' ? (x[header.v]|number: 2) : (x[header.v])}}
        </td>
      </tr>
    </tbody>
  </table>
</div>