0

I've been trying to refactor some code, using a directive instead of the img tags. I want to dynamically change the ng-if state and the src, depending on what value I input in the directive.

for right now the code looks something like:

directive-

'use strict';
angular.module('myApp').directive('listImg', function() {
return {
    retrict: 'E',
    templateUrl: 'templates/list-img.html',
    scope: {
        show: '@',
    },
    link: function($scope) {

        $scope.iconImg;

        if ($scope.show == "opt1") {
            $scope.iconImg = "images/img1.png";
        } else if ($scope.show == "opt2") {
            $scope.iconImg = "images/img2.png";
        } else if ($scope.show == "opt3") {
            $scope.iconImg = "images/img3.png";
        } else if ($scope.show == "opt4") {
            $scope.iconImg = "images/img4.png";
        }

    }
}
});

template-

<img ng-if="show" ng-src="{{iconImg}}" class="list-image">

and then-

<list-img show="{{item.opt1 ? 'opt1' : ''}}"></list-img>

I can't get it to work properly and it does not feel like best practice... It would be great if someone could give some advice on how to improve/rewrite it!

Thanks

Kazordomo
  • 47
  • 1
  • 7

1 Answers1

0

Use ng-if with correct way by identity check of condition, as

<img ng-if="item.opt1!=''" src="{{item.opt1}}" /> and <img ng-if="item.opt1==''" src="noimg.jpg" />

Try it!