2016-09-06 8 views
0

ng-classを特定の背景イメージを持つCSSクラスで更新しようとしています。例:コントローラ内の条件文に基づいてng-classを変更する

<button id="search" ng-class="{travel: travel }">Search</button> 

for(var i = 0; i < arrayLength; i++) { 

    var descriptions = uniqueFilters[i].split(' '); 

     if(descriptions.indexOf('Travel') > -1) { 
      $scope.travel = "travel"; 

      } else { 

       } 
      }} 

文字列が表示されます。私は文字列を取り、文章を個々の単語に分割し、特定の単語がある場合は、クラスを更新して特定の背景イメージを適用します。

これを動作させるにはどうすればよいですか?

+0

あなたが条件として使用しているものは何でも ' ng-class'の場合、 'string'ではなく' boolean'値でなければなりません。他の{ ' '} ' '} '; '場合(descriptions.indexOf( '旅行')> -1){ ' ' =真 ' ' $のscope.travel}:たぶんような何かを行います –

答えて

0

あなたはtrueまたは012のいずれかに評価する必要があるngClassディレクティブに関数を渡すことができます。お使いのコントローラで

<button id="search" ng-class="{travel: travel() }">Search</button> 

:あなたは、あなたのコントローラに機能travelを作成し、あなたのビューでディレクティブにそれを渡すと

// ... your other code 

$scope.travel = function() { 

    for (var i = 0; i < arrayLength; i++) { 

    var descriptions = uniqueFilters[i].split(' '); 

    if (descriptions.indexOf('Travel') > -1) { 

     // we have satisfied our condition 
     // the class 'travel' will be added to the button 
     return true; 

    } 

    } 

    // we didn't satisfy the condition in our loop 
    // the class 'travel' will NOT be added to the button 
    return false; 

} 
+0

あなたはそれをさらに単純化することができます 'return descriptions.indexOf( 'Travel')> -1' –

+0

@DaveVいいえ、それは毎回ループの最初の反復内に戻るでしょう – cnorthfield

+0

ああ、偽がループの外側にあったことをキャッチする、私の悪い –

1

@Dave Vは旅行が真である必要がありますのでNGクラスのディレクティブは、ブール値を必要とする彼のコメントで言ったように:

$scope.travel = true; 

それとも、それが文字列である必要があれば、あなたが何かを行うことができます以下のような:

ng-class="{travel: travel == 'travel' }" 

それは=をホープ)

関連する問題