2012-12-17 7 views
13

何かが真であればクラスを適用しようとしています。ドキュメントはここに私のモックオブジェクトAngularJs:モデルに基づいてクラスを追加する

$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 
     }}      
    ]; 

だとここで私のマークアップですli1 === true場合

favoriteのクラスを追加しようとしhttp://docs.angularjs.org/api/ng.directive:ngClass

に非常に簡単です。

 <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/

は誰が正しい方向に私を指すため、行方不明の依存関係には動作しませんか? :}

答えて

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のではないことを...あなたは厳密に差し込む場合には注意してください=== 'と等しい場合、エラーが発生します。

希望に役立ちます!

+0

私はとても近かった!これは完全に機能します。どうもありがとうございました! –

+2

" - "で区切られたクラスの場合は、クラス名を 'classname'のような引用符で囲んで構文エラーを避けます – imsheth

関連する問題