我在创建动态 HTML 模板时遇到了一些问题。要在表中显示一些数据,我必须区分普通字符串和数组。首先要做的事情是:使用 data-ng-include
将 HTML 模板包含在另一个模板中。带有 Controller 的指令。 Controller 包含我的数据,它本质上是一个具有不同属性的对象。该对象看起来像这样,包含字符串和数组:
$scope.data = {
name: 'tony',
city: 'New York',
friends: ['Ann', 'Ben', 'John Doe'],
postal: 12345
};
还有一个包含属性的匹配数组,用于动态解析信息。
$scope.attributes = [{name: "Name", id: 'name'},
{name: "City", id: 'city'},
{name: "Friends", id: 'friends'},
{name: "Postal-code", id: 'postal'}
];
data
在 HTML
内被解析使用此代码:
<table class="table table-striped">
<tbody>
<tr ng-repeat="attr in attributes">
<td>{{attr.name}}</td>
<td>{{data[attr.id]}}</td>
</tr>
</tbody>
</table>
这对于字符串来说绝对有效,但我必须以某种方式确定 data
的属性是否有效。是一个数组,用于显示某种列表中的单个记录,使用 ng-repeat
记录在案。
我尝试使用Array.isArray(data[attr.id])
与 if
- <script>
内不同变体的子句-标签但没有任何效果。
最后是friends
的数据-属性应该在同一单元格中显示在另一个属性的下面,如下所示:
Here是JsFiddle上的代码
最佳答案
你可以使用 isArray,但不能直接在 ng-show 中。
你可以像这样使用它。
$scope.isArray = angular.isArray;
这样,
<tr ng-repeat="person in persons">
<td ng-repeat="attr in query.attribs">
<span ng-show="isArray(person[attr.id])">
<span ng-repeat="p in person[attr.id]">
{{p}}
</span>
</span>
<span ng-show="!isArray(person[attr.id])">
{{person[attr.id]}}
</span>
</td>
</tr>
这是您的更新Fiddle
关于javascript - AngularJs 在 HTML 模板中分离数组和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891926/