2016-09-06 38 views
0

我正在嘗試使用具有特定背景圖像的CSS類更新ng-class。例如:根據條件語句在控制器中更改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',它需要是一個'boolean'值,而不是'string'。也許這樣做: '如果(descriptions.indexOf( '旅行')> -1){'' $ scope.travel = TRUE;' '}其他{' '}'' }' –

回答

0

您可以傳遞一個函數到ngClass指令,它需要評估要麼truefalse

如果你在你的控制器創建一個函數travel然後將它傳遞到指令在您的視圖:

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

在你的控制器:

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

ahhh,我沒有' t趕上錯誤是在循環之外,我的壞 –

1

正如@戴夫伏在他的評論說,納克級的指令需要一個布爾值,因此旅行社必須是真實的:

$scope.travel = true; 

或者,如果你需要它是一個字符串,你可以這樣做像:

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

希望它可以幫助=)