使用ng-if作为ng-repeat内部的开关?


70

我正在使用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中实现此目标?

Answers:


89

尝试环绕stringshootstoryarticle)与报价'

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

8
只是指出差异(因为我没有立即看到它):答案是用引号将字符串引起来。将它们用作直接文字将不起作用。
Stephan Rauh 2014年

1
以上解决方案奏效了吗?我尝试了相同的方法,但没有成功:(请帮助如何使用ng-if来检查文字
Arun 2014年

这对我也不起作用。即使ng-if='false'ng-show='false'
YasinOkumuş17年


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';
  }
});

http://plnkr.co/edit/HxnirSvMHNQ748M2WeRt?p=preview


这似乎很好。我正在使用后端Laravel构建它。我只是在探索Angularjs。laravel刀片模板化有可能吗?如果您尝试过使用框架?
Anil Sharma 2014年

不幸的是,我对laravel不熟悉。但是,无论如何,只要它的角码,角将处理它在甜蜜的方式肯定
尤金体育

好,谢谢您的帮助。,我肯定会尝试这种方法
Anil Sharma 2014年

@EugeneP是否将角度模板一次在<ng-include />中构建,然后将其用于ng-repeat?还是每次都会从ng-include中获取新模板?
mcranston18 2014年

1
@EugeneP我将对其他任何人回答我自己的问题(^):ng-include被浏览器缓存,因此ng-repeat内的ng-include将被缓存
mcranston18
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.