数据不会出现在使用 AngularJS 创建的表中
Data doesn't appear in table created with AngularJS
在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 页面呈现中。当我尝试显示页面时,我的数据没有出现在表格中......有什么想法可以解决吗?
你应该迭代行数组,因为 Items 是一个对象:
<tbody>
<tr ng-repeat="values in Items.rows">
<td ng-repeat="data in values">{{data}}</td>
</tr>
</tbody>
指令应该做什么?如果你想做我认为你是什么,你不需要它。
你也重复项目,但我认为你需要项目.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>
如果您的指令仅执行的操作是将特定标签替换为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
该变量将设置为您分配给table
元素上items
属性的任何内容。
视图:
<div ng-controller="Controller">
<generic-table items="Items"></generic-table>
</div>
表.html:与上一个相同。
请注意,您还应该将指令的名称更改为 genericTable
或任何您想要的名称,因为在旧场景中table
是一个指令 - 想象一下包括它本身的指令,我想这不是一个好主意。
相关文章:
- AngularJs指令,该指令创建内部有数据对象的新指令
- 我想在AngularJS应用程序中创建一个输入数字框,用户不应该在该框上键入十进制数字.(一个整数输入框)
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- 在angularjs中创建自定义控件的推荐方法
- 如何惯用地手动销毁scope&在AngularJS中重新创建
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- AngularJs从列表中动态创建指令
- 在AngularJS中创建JSON字符串
- 阻止“ng include”创建孤立的作用域.AngularJS
- 创建 AngularJS 指令,如 ngModel 用于数组
- 如何使用自定义指令创建 angularjs 动态模板
- 创建 angularjs 模块
- 为 javascript 数组创建 angularjs 指令,将其转换为复选框列表
- 如何根据文档创建AngularJS控制器
- 如何创建AngularJS指令以在按下回车按钮时提交jquery对话框
- 从现有的javascript代码创建angularjs应用程序
- 正在创建AngularJS对象,该对象在应用程序加载时调用方法
- 如何使用TypeScript创建AngularJs提供程序
- 为什么在 Coffescript 中创建 AngularJS 控制器时使用 @ 符号
- 为什么在使用d3创建AngularJS指令时使用element[0]而不是element ?