2016-07-28 3 views
0

의 상태에 따라 달라 한마디로AngularJS와 DOM 요소는 내가이 간단한 지침을 가지고 지침

app.directive('participants',function(){ 
    return{ 
    restrict:'E', 
    scope:{ 
     allParticipants:"=", 
     appendOption:"=" 
    }, 
    templateUrl:'/templates/participants.html', 
    link: function(scope,element,attr){ 
     scope.$watch('allParticipants',function(value){ 
     if (value){ 
      value.length > 3 ? showShortParticipants() : showFullParticipants() 
     } 
     }); 
    } 
    } 
}); 

을 - 나는 다른 아이의 DOM 요소가 value에 따라 작성하고 싶습니다. 예를 들어, value.length이 3보다 크면 유형 1의 요소를 만들고 유형 2의 요소를 만들지 않으려면 1과 다른 템플릿을 만듭니다.

그 우아한 방법은 무엇입니까?

+0

그리고 어떤 유형의 가능성이 있습니까? 다른 입력 유형? 또는 데이터를 표시하는 다른 방법? 또는...? –

+0

Im은 다른 자식 템플릿을 만들 때, 범위의 결과에 따라 달라집니다 :) – Chenko47

+1

"fullParticipants"뷰에서만 표시되어야하는 요소에 템플릿의'ng-if = "allParticipants.length> 3"'을 사용하면됩니까? – dex

답변

0

당신은 ng-include 지시어를 사용하여 다른 외부 템플릿 URL을로드 할 수 감사합니다. 템플릿 URL의 값은 데이터의 다른 결과에 따라 달라질 수 있습니다.

지시문에 ng-include을 사용하여 제안 template

app.directive('participants', function() { 
    return { 
    restrict: 'E', 
    scope:{allParticipants:"=",appendOption:"="}, 
    link: function($scope) 
    { 
     $scope.$watch('allParticipants', function(value) 
     { 
     // determine template url 
     var tempVal; 
     switch (value){ 
      case 1: 
       tempVal = 'template1'; 
       break; 
      case 2: 
       tempVal = 'template2'; 
       break; 
      default: 
       tempVal = 'templatedefault'; 
       break; 
     }  
     // set scope value 
     $scope.templateURL = 'templates/' + tempVal + '.html';  
     }); 
    }, 
    template: '<ng-include src="templateURL"></ng-include>' 
    }; 
}); 

지시문에 ng-switch을 사용하여 제안 template

app.directive('participants', function() { 
    return { 
    restrict: 'E', 
    scope:{allParticipants:"=",appendOption:"="}, 
    template: '<div ng-switch on="allParticipants">' + 
     '<div ng-switch-when="1">Type 1</div>' + 
     '<div ng-switch-when="2">Type 2</div>' + 
     '<div ng-switch-when="3">Type 3</div>' + 
    '</div>' 
    }; 
}); 

기타 posibilities은 (ng-show 선호) 실시 예 ng-if를 사용 가능

+0

위대한 작품. 고맙습니다 ! – Chenko47

+0

유형별로 외부 HTML 파일을 원하지 않으면 업데이트 된 답변보기 :) –