我正在尝试使用具有特定背景图像的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 {
}
}}
我收到一个字符串数组。我使用字符串,将句子分成单独的单词,然后如果它们有特定的单词,则更新类以应用特定的背景图像。
我怎么让它工作?
正如@Dave V在他的评论中所说,ng-class指令需要一个布尔值,所以travel需要为真:
$scope.travel = true;
或者如果你需要它是一个字符串,你可以这样做:
ng-class="{travel: travel == 'travel' }"
希望能有所帮助=)
您可以将一个函数传递给ngClass
指令,该指令需要计算为true
或false
。
如果你在控制器中创建了一个函数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;
}