AngularJs在HTML模板中分隔数组和字符串 [英] AngularJs seperate array and string in HTML template
问题描述
我在创建动态HTML模板时遇到了一些问题。要在表中显示某些数据,我必须将普通字符串和数组分开。首先要做的事情是:使用带控制器的 data-ng-include
指令将HTML模板包含在另一个模板中。控制器包含我的数据,该数据本质上是具有不同属性的对象。 objcect看起来像这样,包含字符串和数组:
I have a little problem with creating a dynamic HTML template. To display some data in a table, I have to separate between an ordinary String and an Array. First things first: The HTML template is included in another template using the data-ng-include
directive with a controller. The controller contains my data which is essentially an object with different attributes. The objcect looks something like this and contains strings as well as arrays:
$scope.data = {
name: 'tony',
city: 'New York',
friends: ['Ann', 'Ben', 'John Doe'],
postal: 12345
};
还有一个匹配的数组,其中包含动态解析信息的属性。
There is also a matching array with the attributes to parse the information dynamically.
$scope.attributes = [{name: "Name", id: 'name'},
{name: "City", id: 'city'},
{name: "Friends", id: 'friends'},
{name: "Postal-code", id: 'postal'}
];
数据
在<$内解析c $ c> 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
显示一种List中的单个记录。
This works absolutly fine for strings but I have to somehow determine if a attribute of data
is an array to display the single records in a kind of List using ng-repeat
on the record.
我尝试使用 Array.isArray(data [attr.id])
,其中如果
-clause在< script>
-tags内的不同变体中,但没有任何效果。
最后,朋友
-attribute的数据应该在同一个单元格中一个在另一个下面显示如下:
I tried to use Array.isArray(data[attr.id])
with an if
-clause in different variations inside of <script>
-tags but nothing works.
At the end the data of the friends
-attribute should get displayed one below the other in the same cell like this:
这里是JsFiddle上的代码
Here is the code on JsFiddle
推荐答案
你可以isArray但不能直接在里面ng-show。
you can isArray but not directly inside 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>
这是您更新的小提琴
这篇关于AngularJs在HTML模板中分隔数组和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!