Search code examples
javascriptangularjsdata-bindingangular-ng-if

Adding default option to ng-if


In my dropdown menu, there are two options- small and large. When small is selected, a picture shows up; when large is selected, another picture shows up. I want to add a default picture for when nothing is selected (example. page just loaded). But my code below isn't working.

AngularJS, inside controller:

var urls = {
    '': '/images/Default.png', // empty string doesn't work
    Small: '/images/Small.png',
    Large: '/images/Large.png'
};


$scope.getUrl = function (name) {   
    if (urls[name] !== undefined) return urls[name];
};

HTML (size is the ng-model that binds what the user selects from the dropdown):

<div>
    <img ng-src="{{getUrl(size)}}" ng-if="size">
</div>

Solution

  • You need to define your default value for size as default for example. You can use this

    var urls = {
      default: '/images/Default.png',
      Small: '/images/Small.png',
      Large: '/images/Large.png'
    };
    

    and define your size default value as initial value

    $scope.size = 'default';