【发布时间】:2014-05-01 18:07:45
【问题描述】:
我曾尝试在 ng-repeat 中使用 ng-if,但似乎 ng-if 无法正常工作。
我在 StackOverflow 中引用了几个论坛链接,但对我没有帮助。
我使用的是 Angular 版本 1.3.0
HTML
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<script src="/js/lib/angular-1.3.0/angular.js"></script>
<script src="/js/lib/controllers/ifRepeatController.js"></script>
</head>
<body>
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hootsslllll' ">
//differnt template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//differnt template with story data
</div>
<div ng-if="data.type == 'article' ">
//differnt template with article data
</div>
</div>
</body>
</html>
控制器
var myIfRepeat = angular.module('myIfRepeat',[]);
myIfRepeat.controller('IfRepeatController', function ($scope,$http) {
$scope.comments = [
{"_id":"1",
"post_id":"1",
"user_id":"UserId1",
"type":"hoot"},
{"_id":"2",
"post_id":"2",
"user_id":"UserId2",
"type":"story"},
{"_id":"3",
"post_id":"3",
"user_id":"UserId3",
"type":"article"}
];
});
根据第一个条件,第一行不应该显示(下面找到屏幕截图以获取更多参考),但是该行正在显示。
参考链接:Using ng-if inside ng-repeat?
现在我按照建议在 div 中添加了控制器,但是我面临同样的问题
下面我给出了截图供参考。请帮助我如何解决此问题,如果有进一步的说明,请告诉我。
下面提供了使用 Angular 1.3 版本的工作模型的屏幕截图。如果我们使用 Angular 1.0.2,nf-if 将无法正常工作(下面提供了屏幕截图)
角度版本 1.0.2 的屏幕截图
【问题讨论】:
-
小心:
ngIf创建了它的正确范围。 groups.google.com/forum/#!msg/angular/kPRzdcrIzNw/cNaJdguCNeYJ -
@Mik378 抱歉没看清楚
-
你试过用
ng-show代替ngIf吗? -
@Mik378 不,我没有尝试过使用 ng-show,但在这种情况下如何使用 ng-if。
-
如果它与
ng-show一起使用,您的问题肯定来自ng-if的特殊性,它不共享当前范围而是扩展了它。如果它不适用于ng-show,那么您的上下文就是原因。 @j.wittwer 指出了一个非常潜在的原因(上下文原因;))