Chenko47 Chenko47 - 4 months ago 9
AngularJS Question

AngularJS dom element depend on condition in directive

I got this simple 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()
}
});
}
}
});


In short - I would like to create a different child dom element depends on the
value
. For example, if
value.length
bigger than 3, create some element of type 1, and if not to create element of type 2 (different template from 1).

Whats the elegant way to do that?

Thank you

Answer

You could load a different external template URL using the ng-include directive. Value of the template url can be according the different result of the data.

Proposition using ng-include on directive 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>'
  };
});

Proposition using ng-switch on directive 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>'
  };
});

Other posibilities are possible using example ng-if (preferred over ng-show)

Comments