0

I have double checked the 2 threads which are close to the same topic before asking,

  1. How to define ng-src based on condition?

  2. Conditionally change img src based on model data

    but i am not sure these answers are "best practice" - such as defining true-false statements in the {{}} of HTML.

On to my question:
I am trying to load an image based on an array of objects, such that when Key:Value pair "IconOne = 1" it loads icon1, "IconTwo = 2" it loads icon2. The Value is generated from a JSON file so that IconOne can also be 1,2,3,or 4 so it's never consistent.

My current HTML code is:

<ul class="snowSnapText" ng-repeat="mtns in mtnsArray | orderBy:'-lastSnow' | limitTo: 5 ">
      <li><img alt="ski resort logos" class="mtnLogo" ng-src="{{mtns.logoUrl}}"></li>
      <li class="snowSnapName">{{mtns.name}}</li>
      <li class="snowSnapInches">{{mtns.lastSnow}}"</li>
      <li class="snowSnapDeg">{{mtns.hi}}&deg</li>
      <li class="snowSnapIcon"><img alt="weather icon" ng-src="{{getIcons()}}">{{mtns.IconOne}}</li>

My current JS controller looks like:

$scope.getIcons = function(){
if($scope.mtnsArray.IconOne == 1){
    return '../img/icon_sunny.png';
}
else if($scope.mtnsArray.IconOne == 2){
    return '../img/icon_sunny.png';
}
else if($scope.mtnsArray.IconOne == 3){
    return '../img/icon_sunny.png';
}
else {
    return '../img/icon_snow.png';
}
};

I am able to get the ELSE icon to appear in my page for ALL my NG-REPEAT lines, but I feel a bit stuck for some reason and am hoping a new set of eyes can help.

Because my JSON data is being pushed into an Object Constructor from a Factory, what is the best way to access the IconOne value in my Function?

THANKS!

Community
  • 1
  • 1
Phil Lucks
  • 2,704
  • 6
  • 31
  • 57

1 Answers1

0

Looks like the problem is with your $scope.mtnsArray.IconOne mtnsArray is an array not an object ?

when it is an array you cant take the values using a dot ( . )

re write your code like this :

use ng-src="{{getIcons(mtns)}}

$scope.getIcons = function(mtns){
 if(mtns.IconOne == 1){
    return '../img/icon_sunny.png';
 }
 else if(mtns.IconOne == 2){
    return '../img/icon_sunny.png';
 }
 else if(mtns.IconOne == 3){
    return '../img/icon_sunny.png';
 }
 else {
    return '../img/icon_snow.png';
 }
};

or do the following at page load itself

 for(var i = 0 ; i < $scope.mtnsArray.length ; i++ ){

    if($scope.mtnsArray[i].IconOne == 1){
        $scope.mtnsArray[i].imgURL =  '../img/icon_sunny.png';
    }
    else if($scope.mtnsArray[i].IconOne == 2){
        $scope.mtnsArray[i].imgURL =  '../img/icon_sunny.png';
    }
    else if($scope.mtnsArray[i].IconOne == 3){
        $scope.mtnsArray[i].imgURL =  '../img/icon_sunny.png';
    }
    else {
        $scope.mtnsArray[i].imgURL =  '../img/icon_snow.png';
    }
}

and use ng-src="{{mtns.imgURL}}

manoj
  • 3,391
  • 2
  • 20
  • 30