data-ng-repeat with different tags in Angular

时间:2016-04-15 11:13:10

标签: javascript angularjs

There is the following variable in Angular controller:

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

You can see only 2 items in array, but they will be more. So, I need to 'render' this array in HTML. I can use ng-repeat Angular directive, but there is some problem: if item has type 'x' I must render for it, if y - for it. How can I do it? Thanks in advance!

4 个答案:

答案 0 :(得分:1)

使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

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>

答案 2 :(得分:0)

如果表达式为真,你也可以使用ng-hide隐藏元素

<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>

答案 3 :(得分:0)

如果您只想渲染项目类型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>