Using AngularJS, How Can I Choose Not to Render a HTML Element if a Variable is Not Defined?

317 views Asked by At

I'm trying to resolve an issue whereby a HTML element uses a Javascript variable to define the image it should display, but errors on load. Have a look at this line:

<img src="../../Images/{{variableData.data.canEdit}}.png" />

This currently works great, except under the browser's console, it is displaying an error to say that it cannot find the literal string "{{variableData.data.canEdit}}.png". I assume this is because AngularJS is loaded after the HTML elements are rendered by the browser.

How can I work around this?

I did try using the following Angular statement on the element like so:

ng-if="typeof(variableData.data)!=='undefined'"

But I imagine this makes no difference and the browser will still display a not found error message for the .png image.

The page all functions correctly, I just don't want those error messages in the browser's console.

Any ideas?

Many thanks

4

There are 4 answers

1
Luke Welsh On BEST ANSWER

Change

src="<img src="../../Images/{{variableData.data.canEdit}}.png" />"

to

ng-src="<img src="../../Images/{{variableData.data.canEdit}}.png" />" This makes sure it doesn't attempt to load until runtime of the javascript.

Changing the ng-if to just the variable (ng-if="variableData.data.canEdit") will make sure the element is loaded after the variable.

0
Ankur Patel On

You have to put just variable like this

ng-if="variableData.data.canEdit"
0
Izacch On

Thanks to @PierreEmmanuelLallemant for answering this one in the comments.

The solution was to use ng-src within the img element, and then wrap the img element within a div and use an ng-if. Like so:

<div ng-if="variableData.data.canEdit"><img ng-src="../../Images/{{variableData.data.canEdit}}.png" /></div>

Using ng-src ensures that when Angular loads it sets the source attribute. Wrapping the img inside a div with ng-if makes sure that anything inside the div is not rendered until variableData.data.canEdit is defined.

Many thanks

0
AN1BRA On
ng-if="variableData.data"     

this should work fine