angularjs 模块。 products
数组包含 2 个产品对象,它们将作为 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 页面,如果我删除带有实际图像文件名的 images/{{product.image}}
,例如 images/dummy_image_1.jpg
,图像是显示,但如果我改用 angularjs 表达式,则不会显示任何内容。请注意,除了 {{product.image}}
之外,循环中的其他表达式也有效。如果我在其他地方添加 {{product.image}}
,它会正确显示文件名,但在 ng-srs
中使用,如果我查看 html,它不会打印任何内容。我不知道为什么会这样。
<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>
最佳答案
有时使用插值 {{}}
不会评估和更新属性值(这通常发生在 IE 中)。这样做的方法是使用带有插值 {{}}
的 ng-src
指令,这会将 src
添加到 img
评估插值指令后的标记。
标记
<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>
备选
另一种方法是使用 ng-attr
指令添加 attribute
和评估的 value
。这将确保您每次都将内插值分配给 ng-attr
中提到的 attribute
(ng-attr 之后的部分被视为要添加的属性,假设我们有 ng-attr-value="{{someVar}}"
然后 angular 将评估 someVar
然后将该值分配给该元素的 value 属性。
标记
<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>
关于AngularJS 表达式在带有 JSF 的 ng-src 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30701136/