ng-else directive in angularjs

Ramesh Rajendran picture Ramesh Rajendran · Apr 24, 2015 · Viewed 13.5k times · Source

how can we create ngELSE directive as same as ngIF directive?

below code for ngIfDirective. Shall we customize the code for ngELSE?

var ngIfDirective = ['$animate', function($animate) {
  return {
    multiElement: true,
    transclude: 'element',
    priority: 600,
    terminal: true,
    restrict: 'A',
    $$tlb: true,
    link: function($scope, $element, $attr, ctrl, $transclude) {
        var block, childScope, previousElements;
        $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {

          if (value) {
            if (!childScope) {
              $transclude(function(clone, newScope) {
                childScope = newScope;
                clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
                // Note: We only need the first/last node of the cloned nodes.
                // However, we need to keep the reference to the jqlite wrapper as it might be changed later
                // by a directive with templateUrl when its template arrives.
                block = {
                  clone: clone
                };
                $animate.enter(clone, $element.parent(), $element);
              });
            }
          } else {
            if (previousElements) {
              previousElements.remove();
              previousElements = null;
            }
            if (childScope) {
              childScope.$destroy();
              childScope = null;
            }
            if (block) {
              previousElements = getBlockNodes(block.clone);
              $animate.leave(previousElements).then(function() {
                previousElements = null;
              });
              block = null;
            }
          }
        });
    }
  };
}];

Answer

Nidhish Krishnan picture Nidhish Krishnan · Apr 24, 2015

Normally we use like this

normal if-else

if(video == video.large){
    <!-- code to render a large video block-->
}
else{
    <!-- code to render the regular video block -->
}

AngularJS ng-if

<div ng-if="video == video.large">
    <!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
    <!-- code to render the regular video block -->
</div>

But if you are too specific that you want a directive like ng-if, ng-else-if, and ng-else then use ng-elif

Working Demo

 <div ng-if="someCondition">
    ...
  </div>
  <p>
    Some random junk in the middle.
  </p>
  <div ng-else-if="someOther && condition">
    ...
  </div>
  <div ng-else-if="moreConditions">
    ...
  </div>
  <div ng-else>
    ...
  </div>