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!
答案 0 :(得分:1)
使用ng-repeat
和ng-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;
答案 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>