AngularJs在HTML模板

时间:2016-08-11 09:06:02

标签: javascript jquery html angularjs arrays

我在创建动态HTML模板时遇到了一些问题。要在表中显示某些数据,我必须将普通字符串和数组分开。首先要做的事情是:使用带控制器的data-ng-include指令将HTML模板包含在另一个模板中。控制器包含我的数据,该数据本质上是具有不同属性的对象。 objcect看起来像这样,包含字符串和数组:

$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在一种List中显示单个记录。

我尝试在Array.isArray(data[attr.id]) - 标签的不同变体中使用if<script> - 子句,但没有任何作用。 最后,friends - 属性的数据应该在同一个单元格中一个在另一个下面显示,如下所示:

enter image description here

Here是JsFiddle上的代码

3 个答案:

答案 0 :(得分:1)

你可以isArray但不能直接在ng-show中。

你可以这样使用它。

.bottom
{
    height:auto;
    background-color:#5C772A;
    color: white;
    margin-top:30px;
}

所以这样,

 $scope.isArray = angular.isArray;

这是您更新的Fiddle

答案 1 :(得分:1)

如果值是这样的数组,你必须做一些脚本和html更改。更新的小提琴:jsfiddle.net/Lt024p9h/7 /

答案 2 :(得分:0)

做这样的事情。

<tr ng-repeat="person in persons">
   <td ng-repeat="attr in query.attribs">
     <span ng-show="isArray(person[attr.id])">
       {{person[attr.id].toString()}}  
     </span>
     <span ng-show="!isArray(person[attr.id])">
       {{person[attr.id]}}
     </span>
   </td>
</tr>