如何动态更改表列的内容

时间:2014-11-26 22:54:20

标签: javascript html wpf angularjs

鉴于以下HTML片段,我如何根据td创建column的内容。

<div ng-app="" ng-controller="controller" >
    <table>
        <tr>
            <th ng-repeat="column in columns">
                {{ column.header }}
            </th>
        <tr ng-repeat="row in rows">
            <td ng-repeat="column in columns">
                <!-- TODO -->
            </td>
        </tr>
    </table>
</div>

每列可以显示不同类型的数据。例如,一个可能只显示一个字符串,另一个可能包含一个绑定到该行属性的文本输入字段。

我想在列(column.createCell(row))上调用一个函数来创建必要的HTML,然后将结果放在<!-- TODO -->的位置。

在WPF中,我只想将ContentPresenterDataTemplateSelector放在一起,但我不知道Angular中的等价物是什么。我读到了一些名为“ng-bind-html”的东西,这是要走的路吗?

1 个答案:

答案 0 :(得分:1)

没有给出要为每列构建哪种自定义元素,但对于AngularJS中的DOM操作,最佳做法是将其保存在指令中。像这样:

你的HTML中的

<body ng-controller="MainCtrl">
    <table>
      <tr ng-repeat="row in rows">
        <td ng-repeat="column in row">
            <custom-column="column"></custom-column>
        </td>
      </tr>
    </table>    
  </body>

app.js

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

app.controller('MainCtrl', function($scope) {
  // whatever you wanted to define here...
  $scope.rows = ...
  $scope.columns = ...
});

app.directive('customColumn', function() {
  return {
    scope: {
      obj: '=customColumn',
    },

    link: function(scope, element, attrs) {

      var watcher = scope.$watch('obj', function(obj) {
        if (!obj) return;

        // build custom element
        var html = '<div>'+scope.obj.name+'</div>';
        element.html(html);

        // delete watch if you only need to draw once
        watcher();
      });
    }
  }
});
相关问题