13

如果事情属实,只是尝试申请一个课程。该文档非常简短http://docs.angularjs.org/api/ng.directive:ngClass

试图favoriteliif上添加一个类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 等)而实际上不起作用

http://jsfiddle.net/HtJDy/

谁能指出我正确的方向?:}

4

1 回答 1

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……如果插入严格的等于 '===',你会得到一个错误。

希望有帮助!

于 2012-12-17T23:54:45.190 回答