AngularJS expression not working correctly in ng-src with JSF
Angle module. the array products
contains 2 product objects to be added as a property of the controller.
(function () {
var app = angular.module('myApp', []);
var products = [
{
title: "Dummy Title 1",
description: "Dummy Description 1",
image: "dummy_image_1.jpg"
},
{
title: "Dummy Title 2",
description: "Dummy Description 2",
image: "dummy_image_2.jpg"
}
];
app.controller('myController', function () {
this.products = products;
});
})();
JSF page, if I delete images/{{product.image}}
with the actual filename of the image such as images/dummy_image_1.jpg
, the images are displayed, but if I use the angular expression, then nothing is displayed. Note that the other expressions in the loop work besides {{product.image}}
. If I add {{product.image}}
elsewhere, then it displays the filename correctly, but used in ng-srs
, it doesn't print anything if I go through the html. I don't know why this is so.
<h:form>
<div class="container" ng-controller="myController as controller">
<div class="row">
<div class="col-sm-offset-10">
Hello <b><h:outputText value="#{user.userName}"/></b><br/>
<h:commandLink action="cart" value="Cart"/>
</div>
</div>
<hr/>
<div ng-repeat="product in controller.products">
<div class="row">
<div class="media">
<div class="media-left">
<img class="media-object" ng-src="images/{{product.image}}"/> <!--If I replace that expression with a the image file name, it shows the image -->
</div>
<div class="media-body">
<h4 class="media-heading">{{product.title}}</h4>
<span class="caption">{{product.description}}</span><br/>
<h:commandLink action="cart" value="Add to cart"/>
</div>
</div>
</div>
</div>
</div>
</h:form>
source to share
Sometimes using interpolation {{}}
will not evaluate and update the attribute value (most often this happens in IE). The way to do this is with an ng-src
interpolation directive {{}}
that will add src
to the tag img
after the interpolation evaluation directive.
Markup
<div class="media-left">
<img class="media-object" ng-src="{{'images/'+product.image}}"/>
<!--If I replace that expression with a the image file name, it shows the image -->
</div>
Alternative
Another way would be to use the directive ng-attr
that adds attribute
with evaluation value
. This will ensure you every time an interpolated value has been assigned to the attribute
one mentioned in ng-attr
(the part after ng-attr is treated as an added attribute, suppose we have ng-attr-value="{{someVar}}"
, then angular will evaluate someVar
and then assign that value to the attribute value for that element.
Markup
<div class="media-left">
<img class="media-object" ng-attr-src="{{'images/'+product.image}}"/>
<!--If I replace that expression with a the image file name, it shows the image -->
</div>
source to share