我刚刚开始使用 Angular JS。我将它与 CodeIgniter 一起使用。如果条件匹配,我正在尝试添加 {class="active"}。
我正在尝试将事件类添加到 <li>
如果其标题与 url 的最后一段匹配。
即
if(title of this nav_menu matches with the last uri segment)
add "active" class
else
do nothing
我的代码如下:
header.php
<ul class="nav navbar-nav" ng-app="" ng-controller="menuController">
<li ng-repeat="x in menus" ng-class="{'active': x.name = scope}">
<a ng-href="http://{{ x.link}}">{{ x.name }}</a>
</li>
</ul>
页脚.php
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
function menuController($scope) {
$scope.menus = [ {
name : "Home",
link : "projects/test/home"
}, {
name : "Daily Special",
link : "projects/caesar/daily-especial"
}, {
name : "Menu",
link : "projects/test/menu"
}, {
name : "Special",
link : "projects/test/special"
}, {
name : "Gallery",
link : "projects/test/gallery"
}, {
name : "About us",
link : "projects/test/about-us"
}, {
name : "Contact",
link : "projects/test/contact"
} ];
$scope.current = '<?php echo $this->uri->segment(2); ?>';
}
</script>
我认为有问题的步骤是 $scope.current = 'uri->segment(2); ?>';
最佳答案
这是 ng-class 的工作原理,如下例所示
ng-class="{ 'active': menu.IsCurrentTab, 'inactive': !menu.IsCurrentTab }"
如果范围变量 menu
具有 IsCurrentTab
值 true
,则将添加 class active
。否则将使用inactive
类。
对于你的情况,首先我不知道你的这段代码是做什么的
$scope.current = '<?php echo $this->uri->segment(2); ?>';
如果这将当前菜单名称放入$scope.current
变量中,那么您需要做的就是
<li ng-repeat="x in menus" ng-class="{'active': x.name == current}" >
希望这有帮助。
编辑:
希望您检查该值是否已填充到您的 $scope.current 变量中。
关于javascript - 在 Angular JS 中如果条件匹配则添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26879892/