ngSwitch vs. ngIf

by lsiv568

HTML

<div ng-app="test" ng-controller="TestCtrl">
    <input type="text" ng-model="typeId" />
    <div ng-switch on="typeId">
        <div ng-switch-when="1">Hello</div>
        <div ng-switch-when="2">Goodyble</div>
        <div ng-switch-when="3">whatever</div>
    </div>
    <div ng-if="typeId == constants.type.a">Hello</div>
    <div ng-if="typeId == constants.type.b">Goodyble</div>
    <div ng-if="typeId == constants.type.c">whatever</div>
</div>
<!-- Example showing how ng-switch only sees the value you provide it via the on attribute
     This means you can't use variables in your ng-switch-when and must use constants
     If variables are cleaner/increase readability, you must use an ng-if!
    <div ng-switch on="typeId">
        <div ng-switch-when="constants.type.a">Hello</div>
        <div ng-switch-when="constants.type.b">Goodyble</div>
        <div ng-switch-when="constants.type.c">whatever</div>
    </div>
 -->

JavaScript

var app = angular.module('test', []);
app.controller('TestCtrl', function($scope) {
    $scope.typeId = 1;
    
    $scope.constants = {
        type: {
            a: 1,
            b: 2,
            c: 3
        }
    };
});