如果某事是真的,只是尝试应用一个类。关于http://docs.angularjs.org/api/ng.directive:ngClass
的文档非常简短如果favorite
li
上添加1 === true
课程
这是我的模拟对象
$scope.restaurantListFromSearch = [
{restaurantName: "Zocala",
details: {
image: "http://placehold.it/124x78",
url: "#",
cuisineType: ["Sandwiches", "American", "BBQ"],
description: "Modern, healthy, awesome BBW",
priceRange: "$",
userFavorite: 0
}},
{restaurantName: "Subway",
details: {
image: "http://placehold.it/124x78",
url: "#",
cuisineType: ["Sandwiches", "American", "BBQ"],
description: "Modern, healthy, awesome BBW",
priceRange: "$",
userFavorite: 1
}},
{restaurantName: "Hungry Howies",
details: {
image: "http://placehold.it/124x78",
url: "#",
cuisineType: ["Sandwiches", "American", "BBQ"],
description: "Modern, healthy, awesome BBW",
priceRange: "$",
userFavorite: 0
}}
];
这是我的标记。
<ul>
<li ng-repeat="restaurant in restaurantListFromSearch" ng-class="{restaurant.details.userFavorite === 1: favorite}">
<img src="{{restaurant.details.image}}" alt="{{restaurant.restaurantName}}">
<div class="details">
<a href="{{restaurant.details.url}}">{{restaurant.restaurantName}}</a>
<span class="cuisine-type">{{restaurant.details.cuisineType}}</span>
<p>{{restaurant.details.description}}</p>
<span class="price-rating">{{restaurant.details.priceRange}}</span>
</div>
<div class="clear"></div>
</li><!-- end restaurant result -->
</ul>
为了便于阅读,添加了jsFiddle,由于缺少依赖项(requireJs等)而无法正常工作
有人能指出我正确的方向吗? :}
答案 0 :(得分:27)
ngClass正在寻找要评估的角度表达式,“评估结果可以是表示空格分隔的类名,数组或类名映射到布尔值的字符串。”
对于你的例子来说,它与你的想法有点相反,左边部分是你要添加的类,右边是布尔表达式。
<li ng-repeat="restaurant in restaurantListFromSearch" ng-class="{ favorite : restaurant.details.userFavorite == 1}">
像这样的对象映射允许您根据需要拥有多个类:
<li ng-repeat="restaurant in restaurantListFromSearch" ng-class="{ favorite : restaurant.details.userFavorite == 1, otherClass: otherBooleanExpression }">
另请注意,布尔表达式不是JavaScript ......如果插入严格等于'===',则会出错。
希望有所帮助!