根据作用域值添加和删除活动类



嗨,我对angularjs了解不多。在我的页面加载中,我根据location.hash将范围值定义为true/false

if(location.hash=='#en'){
$scope.selectedLang=true;
}
else{
$scope.selectedLang=false;
}

selectedLang为真时,我需要将活动类添加到li中的a元素中。 当slectedLang为假时,我需要删除a元素中的活动类。

<li><a href="#eng" >english</a></li>
<li><a href="#hin" >hindi</a></li>

默认情况下,selectedLang应为 true。我怎样才能得到它?请帮忙吗?

你需要像这样使用 ng-class,

<li><a href="#eng" ng-class="{'active' : selectedLang}">english</a></li>
<li><a href="#hin" ng-class="{'active' : !selectedLang}">hindi</a></li>

如果你想直接拥有样式而不是类,你需要像这样使用,

<li><a href="#eng" ng-style="{ color :  selectedLang ? 'blue' : '#ddd', background: selectedLang ? 'red' : '#fff'}">english</a></li>
<li><a href="#hin" ng-style="{ color :  selectedLang ? 'blue' : '#ddd', background: selectedLang ? 'red' : '#fff'}" >hindi</a></li>

并默认设置 selectedLang = true

$scope.selectedLang=true;
if(location.hash != '#en'){
$scope.selectedLang=false;
}

您可以将三元运算符与ng-class一起使用,如下所示

<a href="#eng" ng-class="selectedLang ? 'active' : ''">english</a>

参考

最新更新