数据ng在Angular中用不同的标签重复

data-ng-repeat with different tags in Angular

本文关键字:标签 ng Angular 数据      更新时间:2024-07-05

角度控制器中有以下变量:

$scope.items = [
  { title: 'x', type: 'x'},
  { title: 'y', type: 'y'}
];

数组中只能看到2个项目,但它们会更多。因此,我需要在HTML中"呈现"这个数组。我可以使用ng repeat Angular指令,但有一些问题:如果项的类型是"x",我必须为它渲染,如果是y,我该怎么做?提前感谢!

ng-repeat中放置一个:filter,如下所示:

var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
  $scope.items = [{
    title: 'x',
    type: 'x'
  }, {
    title: 'y',
    type: 'y'
  }, , {
    title: 'another x',
    type: 'x'
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
  <div>Only items of type 'x':</div>
  <ul>
    <li ng-repeat="item in items | filter: {type: 'x'} ">{{item.title}}</li>
  </ul>
</div>

使用ng-repeatng-switch:的组合

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
  $scope.items = [
    { title: "TestX", type: "x" },
    { title: "TestY", type: "y" }
  ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="item in items">
    {{ item.title }}
    <div ng-switch="item.type">
      <div ng-switch-when="x">
        HTML for type x
      </div>
      <div ng-switch-when="y">
        HTML for type y
      </div>
    </div>
  </div>
</div>

如果表达式为true ,您也可以使用ng隐藏元素

<div ng-repeat="item in items" >
        <div ng-hide="item.type == 'y'">
        {{ item.type }}
        </div>
        <div ng-hide="item.type == 'x'">
        {{ item.type }}
        </div>
</div>

如果只想为项目类型x进行渲染,则用户可以在ng-repeat中"筛选",也可以使用ng-if

<div ng-repeat="item in items"> 
    <div ng-if="item.type==='x'">
       <p>Item for type x</p>
    </div>
</div>