Using ng-if as a switch inside ng-repeat?

混江龙づ霸主 提交于 2019-11-26 12:06:43

问题


I am working on Angular app. I tried to use ng-if and switch inside ng-repeat but didn\'t succeed. I have data like:

   **[{\"_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 = data mentioned above
and my Html like :

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

How can I achieve this thing in Angular?


回答1:


Try to surround strings (hoot, story, article) with quotes ':

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



回答2:


This one is noteworthy as well

<div ng-repeat="post in posts" ng-if="post.type=='article'">
  <h1>{{post.title}}</h1>
</div>



回答3:


I will suggest move all templates to separate files, and don't do spagetti inside repeat

take a look here:

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



来源:https://stackoverflow.com/questions/21751676/using-ng-if-as-a-switch-inside-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!