绑定元素时从范围对象添加格式

时间:2015-12-22 12:29:06

标签: javascript angularjs

我有一个表,它是从我在控制器中创建的数组中构建的。在尝试绑定时,我想添加格式,例如|数字,来自我的对象数组。

所以,在tbody里面的td元素中,我想使用像

这样的东西
  

row [column.rowValue] | column.filter

我尝试过使用{{}},还尝试了ng-bind-template等等。

我该怎么做?

JSFIDDLE

HTML:

<script data-require="angular.js@*" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


<div ng:controller="MyCtrl">

<table class="table table-striped table-hover table-responsive table-bordered" border="1">
        <thead style="font-weight: bold;">
            <tr>
                <th class="text-right" ng-repeat="column in columns" ng-bind="column.rowHeader"></th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="row in rows">
                <td ng-repeat="column in columns" ng-bind="row[column.rowValue] | column.filter"></td> <--doesnt work
            </tr>
        </tbody>
    </table>


</div>

JS:

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


 function MyCtrl($scope) {
  $scope.columns = [
    { checked: true, rowValue: 'value1', rowHeader: 'Value1', filter: 'number' },
    { checked: true, rowValue: 'value2', rowHeader: 'Value2', filter: 'number' },
    { checked: true, rowValue: 'ModelName', rowHeader: 'Name' }
];

$scope.rows = [
  { value1: 100, value2: 5, ModelName: "This is a cell value" },
  { value1: 15, value2: 5, ModelName: "This is a cell value2" },
  { value1: 38, value2: 2, ModelName: "This is a cell value3" }
  ];

}

1 个答案:

答案 0 :(得分:1)

使用控制器中的函数格式化值,如果需要使用自定义过滤器,请注入$filter服务。

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


function MyCtrl($scope, $filter) {
    $scope.columns = [
        { checked: true, rowValue: 'value1', rowHeader: 'Value1', filter: 'number' },
        { checked: true, rowValue: 'value2', rowHeader: 'Value2', filter: 'number' },
        { checked: true, rowValue: 'ModelName', rowHeader: 'Name' }
    ];

    $scope.formatRow = function(value, filterName){
        return $filter(filterName)(value);
    };

    $scope.rows = [
      { value1: 100, value2: 5, ModelName: "This is a cell value" },
      { value1: 15, value2: 5, ModelName: "This is a cell value2" },
      { value1: 38, value2: 2, ModelName: "This is a cell value3" }
      ];

    }

HTML

<tbody>
    <tr ng-repeat="row in rows">
       <td ng-repeat="column in columns" ng-bind="formatRow(row[column.rowValue], column.filter)"></td> 
                </tr>
</tbody>