AngularJS dom 元素取决于指令中的条件

AngularJS dom element depend on condition in directive

我得到了这个简单的指令:

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

简而言之 - 我想根据 value 创建一个不同的子 dom 元素。例如,如果 value.length 大于 3,则创建一些类型 1 的元素,如果不创建类型 2 的元素(与 1 不同的模板)。

这样做的优雅方法是什么?

谢谢

您可以使用 ng-include 指令加载不同的外部模板 URL。模板的值url可以根据数据的不同结果

在指令 template

上使用 ng-include 的命题
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>'
  };
});

在指令 template

上使用 ng-switch 的命题
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>'
  };
});

使用示例 ng-if 可以实现其他可能性(优先于 ng-show