Change the img src path using NG-Model to & lt; SELECT & gt; Mark

advertisements

I'm new to AngularJS, I've started learning it since yesterday.

My HTML code:

<select ng-model="myImage">
        <option selected disabled>Make selection</option>
        <option value="earth">Earth</option>
        <option value="moon">Moon</option>
        <option value="sun">Sun</option>
</select>

{{myImage}}
<img ng-src="{{myImage}}">

My JavaScript code:

(function() {
    app = angular.module('app', []);
    app.controller("imgController", function($scope) {
        function getImageIdOrName(param) {
            var imageNames = ["earth", "moon", "sun"];
            if (typeof param === "number") {
                return imageNames[param - 1];
            }
            if (typeof param === "string") {
                for (var i = 0; i <= imageNames.length; i++) {
                    if (imageNames[i] == param) {
                        return pad((i+1), 3);
                    }
                }
            }
        }

        function pad(number, length) {
            var str = '' + number;
            while (str.length < length) {
                str = '0' + str;
            }
            return str;
        }

        $scope.myImage = "img/" + getImageIdOrName($scope.myImage) + "png";
   });
}());

I'm trying to display the image which is selected in the <select> tag, the images are named like:

001.png (Earth)
002.png (Moon)
003.png (Sun)

I know that I can fix this, by doing it like:

<select ng-model="myImage">
        <option selected disabled>Make selection</option>
        <option value="001">Earth</option>
        <option value="002">Moon</option>
        <option value="003">Sun</option>
</select>

<img ng-src="img/{{myImage}}.png">

But what I really want to do is to pass names in the value of <option> instead of image IDs and then I want to use my getImageIdOrName(param) function to convert the name into ID and use the id for <img> tag's src attribute.

I've tried doing the following in my controller: $scope.myImage = "img/" + getImageIdOrName($scope.myImage) + "png";

But that doesn't seem to work, the ng-model is returning the selected value of <option> instead of doing$scope.myImage = "img/" + getImageIdOrName($scope.myImage) + "png";

Can somebody tell me what I'm doing wrong and show me a solution for this?


All you need is

<img ng-src="img/{{getImageIdOrName()}}.png">

Your code doesn't make much sense, because it initializes $scope.myImageonly once, when the controller is instanciated. You need to get a new value each time the selection changes, and the easiest way to do that is to call the function from the view, as shown above.

Another option is to use ng-change on the select in order to invoke a function that changes the value of myImage every time the selection changes.