【问题标题】:AngularJs: Add class based on ModelAngularJs:基于模型添加类
【发布时间】:2012-12-17 23:14:44
【问题描述】:

如果某事是真的,只是尝试应用一个类。关于http://docs.angularjs.org/api/ng.directive:ngClass的文档很简短

尝试在li 上添加favorite 类,如果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/

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

【问题讨论】:

    标签: json angularjs


    【解决方案1】:

    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...如果插入严格等于 '===',则会收到错误消息。

    希望有帮助!

    【讨论】:

    • 敬畏,我是如此接近!这完美地工作。非常感谢!
    • 对于以“-”分隔的类,将类名放在引号中,如“类名”以避免语法错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多