Mordred
Mordred

Reputation: 3941

Dynamically loading image resource in angular directive always errors on initial load

I've got a directive I built to convert 3-digit ISO-3316 country codes into a flag and the country name. I use it like so:

<country-with-flag data="840">

My directive looks like this:

.directive('countryWithFlag', ['countryCodes', function(countryCodes) {
    return {
        scope: {
            data: '='
        },
        restrict: 'E',
        template: '<img src="assets/images/flags/{{data | numericToAlphaCode}}.png"> {{data | numericToCountry}}',
    }
}])

numericToAlphaCode is a filter which would convert 840 into the 3316-alpha2 code which is "US" in this instance.

The directive results in this: Flag & country name

This works perfectly, except that when the page loads I have an error in the console before angular converts the expression into something useful:

error

Why is this occurring and how can I avoid this error from being generated? I assume I need to do something in the link but I'm a little confused as to how that would work, especially because the error occurs before link even gets called.

Upvotes: 2

Views: 2223

Answers (1)

Austin Greco
Austin Greco

Reputation: 33544

try using ng-src, it should prevent loading of the asset until the string is interpolated

template: '<img ng-src="assets/images/flags/{{data | numericToAlphaCode}}.png"> {{data | numericToCountry}}',

Upvotes: 3

Related Questions