Programing

ng-if를 ng-repeat 내부의 스위치로 사용합니까?

lottogame 2020. 11. 10. 07:43
반응형

ng-if를 ng-repeat 내부의 스위치로 사용합니까?


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에서 어떻게이 일을 할 수 있습니까?


서라운드보십시오 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>

이것도 주목할 만합니다

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

모든 템플릿을 별도의 파일로 옮기고 반복 내부에서 spagetti하지 마십시오.

여기를보세요 :

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

참고 URL : https://stackoverflow.com/questions/21751676/using-ng-if-as-a-switch-inside-ng-repeat

반응형