如何将columnNames映射到表数据并仅在uigrid中显示该数据

时间:2016-04-29 04:42:54

标签: angularjs angularjs-directive angularjs-scope angular-ui-router angular-ui-grid

我在属性中动态获取columnNames,我只想显示该对象内的属性。

这是我的columnNames

  $scope.columnNames=[
{"field":"firstName"},
{"field":"lastName"},
{"field":"id"},//i can get "id" or "name" or anything it comes dynamically 
{"field":"employed"}
];

我得到这样的数据 $scope.gridOptions.data = [ { "firstName": "Cox", "lastName": "Carney", "id": "{'id':'1','name':'Syed'}", "employed": true }, { "firstName": "Lorraine", "lastName": "Wise", "id": "{'id':'2','name':'Rasheed'}", "employed": false }, { "firstName": "Nancy", "lastName": "Waters", "id": "{'id':'3','name':'Emir'}", "employed": false } ];

当我运行时,我会在"{'id':'3','name':'Emir'}"列中获取整个对象id,但我只想在该列中显示该id属性值。 这是我的傻瓜http://plnkr.co/edit/AMeTxuMMBmfVt9f0t7HZ?p=preview

2 个答案:

答案 0 :(得分:0)

请参阅此plnkr

添加以下代码以将json从json解析为id字段

angular.forEach($scope.gridOptions.data, function(value, key) {
    var parsedId = angular.fromJson(value.id.replace(/'/g, '"')); 
    value.id = parsedId.id;
  });

另外,好像你的json是'删除而不是",所以我不得不替换字符串,以便可以解析JSON但是如果你得到正确的JSON表单服务器,你不需要这样做。 希望这有帮助

答案 1 :(得分:0)

尝试在cellTemplate中使用$scope.columnNames

只需将cellTemplate: '<span>{{COL_FIELD[col.field]添加到$scope.columnNames,就像这样:

  $scope.columnNames=[
      {"field":"firstName"},
      {"field":"lastName"},
      {"field":"id", cellTemplate: '<span>{{COL_FIELD[col.field]}}</span>'}, //this cellTemplate works for "id" or "name" or anything
      {"field":"employed"}
    ];

由于动态获得$scope.columnNames,您可以像这样添加 cellTemplate

$scope.columnNames[2].cellTemplate='<span>{{COL_FIELD[col.field]}}</span>';

请参阅此plnkr