2016-07-28 44 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

我正在谈论创建不同的子模板,取决于范围的结果:) – Chenko47

+1

只需在模板中使用'ng-if =“allParticipants.length> 3”'在仅应显示在“fullParticipants”视图中的元素上? – 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-if(优于ng-show

+0

效果很好。谢谢 ! – Chenko47

+0

如果你不希望每种类型的外部html文件,请参阅更新的答案:) –