【问题标题】:AngularJS directive with ngTransclude not showing {{bound}} content带有 ngTransclude 的 AngularJS 指令不显示 {{bound}} 内容
【发布时间】:2014-11-26 10:02:30
【问题描述】:

我正在尝试创建一个 Angular 指令,该指令创建我希望在我的应用程序周围使用的表的标准化结构。

我想在 HTML 中声明指令时指定 tr 的结构,以便根据传入的数据有不同的布局。但是,我似乎无法获取 ng-transclude 的内容实际渲染。

Plunker:Example

我想要以下内容:

<custom-table table="data">
  <td>
    {{row.Username}}
  </td>
  <td>
    {{row.FirstName}}
  </td>
  <td>
    {{row.LastName}}
  </td>
</custom-table>

被注入到模板内。

如何让 {{row.Username}} 等标签在 Angular 指令的 ng-transclude 中解析?

Edit1:我认为这是我刚刚发现的一个类似问题,尽管大多数投票最多的答案似乎建议避免在指令中使用 table、tr、td 等:\

【问题讨论】:

    标签: angularjs angular-directive angularjs-ng-transclude


    【解决方案1】:

    这不能回答你的问题,但我认为这是一种更通用的方式来做你想做的事。

    首先将要显示的列列表传递给指令:

    <custom-table table="data" columns="columns">
    </custom-table>
    

    在您的控制器中:

    app.controller('MainCtrl', function($scope) {
      $scope.data = [
        {Username: "Test1", FirstName: "Bill", LastName: "Jones"}, 
        {Username: "Test2", FirstName: "Sophie", LastName: "O'Grady"}, 
        {Username: "Test3", FirstName: "Tim", LastName: "Cross"}
        ];
    
      $scope.columns = ["Username", "FirstName", "LastName"]
    });
    

    在你的指令中:

    app.directive('customTable', ['$compile', function($compile){
      return {
        restrict: 'E',
        templateUrl: 'tableTemplate.html',
        scope: {
          table: '=',
          columns: '='
        }
      };
    }]);
    

    最后将您的模板更改为:

    <div>
      <table>
        <thead>
          <tr>
            <th ng-repeat="col in columns">{{ col }}</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="row in table">
            <td ng-repeat="col in columns">
              {{ row[col] }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    

    这是更新的 plunker:http://plnkr.co/edit/dYwZWD2jB2GsmnvmuSbT

    【讨论】:

    • 为建议干杯;我已经有了一个通用的解决方案,它的功能类似于你所建议的:) 我只是为了这个问题创建了一个简单的例子:)
    【解决方案2】:

    我找到了一种解决方法,可以为我解决问题。

    我已经用一个工作示例更新了 plunker。我必须创建一个指令:

    app.directive('myTransclude', function() {
        return {
            compile: function(tElement, tAttrs, transclude) {
                return function(scope, iElement, iAttrs) {
                    transclude(scope.$new(), function(clone) {
                        iElement.append(clone);
                    });
                };
            }
        };
    });
    

    我在 cmets 中发现了问题 here

    我还必须更新指令,使其使用基于 CSS/div 的表格,而不是使用实际的 HTML 表格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2013-02-05
      相关资源
      最近更新 更多