我正在开发Angular应用。我尝试使用ng-if并在 ng-repeat 内切换,但没有成功。我有以下数据:
**[{"_id":"52fb84fac6b93c152d8b4569",
"post_id":"52fb84fac6b93c152d8b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"hoot",},
{"_id":"52fb798cc6b93c74298b4568",
"post_id":"52fb798cc6b93c74298b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"story",},
{"_id":"52fb7977c6b93c5c2c8b456b",
"post_id":"52fb7977c6b93c5c2c8b456a",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"article",},**
$ scope.comments =上面提到的数据
和我的Html一样:
<div ng-repeat = "data in comments">
<div ng-if="hoot == data.type">
//differnt template with hoot data
</div>
<div ng-if="story == data.type">
//differnt template with story data
</div>
<div ng-if="article == data.type">
//differnt template with article data
</div>
</div>
如何在Angular中实现这个功能?
答案 0 :(得分:88)
尝试用引号strings
包围hoot
(story
,article
,'
):
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hoot' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//different template with story data
</div>
<div ng-if="data.type == 'article' ">
//different template with article data
</div>
</div>
答案 1 :(得分:76)
这个也是值得注意的
<div ng-repeat="post in posts" ng-if="post.type=='article'">
<h1>{{post.title}}</h1>
</div>
答案 2 :(得分:12)
我建议将所有模板移动到单独的文件中,不要在重复内部执行意大利面条
看看这里:
html:
<div ng-repeat = "data in comments">
<div ng-include src="buildUrl(data.type)"></div>
</div>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.comments = [
{"_id":"52fb84fac6b93c152d8b4569",
"post_id":"52fb84fac6b93c152d8b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"hoot"},
{"_id":"52fb798cc6b93c74298b4568",
"post_id":"52fb798cc6b93c74298b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"story"},
{"_id":"52fb7977c6b93c5c2c8b456b",
"post_id":"52fb7977c6b93c5c2c8b456a",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"article"}
];
$scope.buildUrl = function(type) {
return type + '.html';
}
});