0

AngularJS 中的指令有一些问题。

我有以下 HTML 代码:

<div ng-controller="Controller">
<table>
    <thead>
    .......
    </thead>
    <tfoot>
    .......
    </tfoot>
    <tbody>
        <tr ng-repeat="values in Items.rows">
            <td ng-repeat="data in values">{{data}}</td>
        </tr>
    </tbody>
</table>
</div>

我的元素的控制器:

var MyApp = angular.module('MyApp', []);
Application.controller('Controller', ['$scope', '$filter', function($scope, $filter) {

// Some logic
$scope.Items = {

     head: ["id", "Name", "Age"],

     rows: [
             ["1", "Bob", "23"],
             ["2", "Sam", "23"],
             ["3", "Joe", "23"]
           ]
     };
           // Some other logic
    }
}

最后是指令:

Application.directive('Table', function() {
  return {
           restrict: 'E',
           replace: true,
           scope: {},
           templateUrl: 'Table.html'
         }
});

问题在于 HTML 页面呈现。当我尝试显示页面时,我的数据没有出现在表格中......有什么解决方法的想法吗?

4

3 回答 3

0

您应该迭代 rows 数组,因为 Items 是一个对象:

<tbody>
        <tr ng-repeat="values in Items.rows">
            <td ng-repeat="data in values">{{data}}</td>
        </tr>
    </tbody>
于 2013-09-30T11:57:13.973 回答
0

该指令应该做什么?如果您正在尝试做我认为您是您的事情,那么您不需要它。

你也重复项目,但我认为你需要 items.rows:

<div ng-controller="Controller">
<table>
    <thead>
    .......
    </thead>
    <tfoot>
    .......
    </tfoot>
    <tbody>
        <tr ng-repeat="values in Items.rows">
            <td ng-repeat="data in values">{{data}}</td>
        </tr>
    </tbody>
</table>
</div>
于 2013-09-30T11:57:55.867 回答
0

如果你的指令只做的是用 Table.html 替换特定的标签,那么我认为你应该使用ng-include,例如以这种方式:

看法:

<div ng-controller="Controller">
    <div ng-include="'Table.html'">
    </div>
</div>

表.html:

<table>
    <thead>
    .......
    </thead>
    <tfoot>
    .......
    </tfoot>
    <tbody>
        <tr ng-repeat="values in Items.rows">
            <td ng-repeat="data in values">{{data}}</td>
        </tr>
    </tbody>
</table>

但是,如果你真的想要一个指令(我的意思是“如果你想使用链接/编译函数并且做的不仅仅是加载模板”),你应该知道作用域如何与指令一起工作。首先,scope: {}将为指令创建一个新的隔离范围,该范围为空(因此Items变量不可见)。您可以摆脱隔离范围(通过保持scope未设置),或者,我认为是一个更好的解决方案,写:

scope: {
    items: '&'
}

它将为此指令创建一个新的隔离范围,但在此范围内将有一个items变量,该变量将设置为您分配给元素items属性的任何table内容。

看法:

<div ng-controller="Controller">
    <generic-table items="Items"></generic-table>
</div>

Table.html:同上。

请注意,您还应该将指令的名称更改为genericTable或任何您想要的名称,因为在旧场景中table是一个指令 - 想象一个包含自身的指令,我想这不是一个好主意。

于 2013-10-01T07:54:58.260 回答