Ng-class不能切换class的开关

ng-class is not toggling class on/off

本文关键字:开关 class 不能 Ng-class      更新时间:2023-09-26

我有一个项目,应该在路径改变时打开/关闭类,但由于某种原因它不起作用。我从另一个项目复制并粘贴了它,它可以在那里工作,但由于某种原因它不能在这里工作。

这是控制器:

app.controller('AdminNav', function($scope, $location){
    // Highlight navigation links
    $scope.isActive = function(viewLocation){
        var regexp = new RegExp(viewLocation + ".+");
        return regexp.test($location.path());
    };
});

这里是html:

<div class="collapse navbar-collapse" id="admin-side-nav" ng-controller="AdminNav">
    <ul class="nav nav-pills nav-stacked">
        <li ng-class="{active: isActive('/dashboard')}">
            <a href="/dashboard"><i class="glyphicon glyphicon-home"></i> Home</a>
        </li>
        <li ng-class="{active: isActive('/dashboard/clicks')}">
            <a href="/dashboard/clicks"><i class="glyphicon glyphicon-hand-up"></i> Clicks</a>
        </li>
        <li ng-class="{active: isActive('/dashboard/uploads')}">
            <a href="/dashboard/uploads"><i class="glyphicon glyphicon-upload"></i> Uploads</a>
        </li>
        <li ng-class="{active: isActive('/dashboard/forms')}">
            <a href="/dashboard/forms"><i class="glyphicon glyphicon-list"></i> Forms</a>
        </li>
    </ul>
</div>

当我点击其中一个链接的url改变,但active类停留在第一个li,我不知道为什么…任何想法吗?

这里是所有的javascript:

var app = angular.module('EDAdmin', ['ngRoute']);
app.config(function($routeProvider, $locationProvider){
    // Prepare for html5 mode
    $locationProvider.hashPrefix('!');
    $locationProvider.html5Mode(true);
    // Setup routing
    $routeProvider.when('/dashboard/', {
        templateUrl: '/templates/dashboard/default.html'
    }).when('/dashboard/clicks', {
        templateUrl: '/templates/dashboard/default.html'
    }).when('/dashboard/uploads', {
        templateUrl: '/templates/dashboard/default.html'
    }).when('/dashboard/forms', {
        templateUrl: '/templates/dashboard/default.html'
    }).otherwise({
        redirectTo: '/dashboard'
    });
});

app.controller('AdminNav', function($scope, $location){
    $scope.active = '';
    // Highlight navigation links
    $scope.isActive = function(viewLocation){
        var regexp = new RegExp(viewLocation + ".+");
        return regexp.test($scope.active);
    };
    $scope.$on('$routeChangeSuccess', function(){
        $scope.active = $location.path();
    })
});

问题是您构造了不正确的正则表达式。例如,当您单击第二项时,正则表达式将为

/'/dashboard'/clicks.+/

而位置路径为

/dashboard/clicks

显然,因为.+的regexp不匹配给定的路径,但确实匹配/dashboard

更可靠的解决方案是使用当前$route.current对象的regexp属性,它被Angular内部用于这个目的——route to location path mapping:

$scope.isActive = function(viewLocation) {
    if ($route.current && $route.current.regexp) {
        return $route.current.regexp.test(viewLocation);
    }
    return false;
};

如果你为/dashboard/clicks路由记录$route.current.regexp,你会看到它看起来像这样:

/^'/dashboard'/clicks$/

所以你可以看到区别-你需要将字符串匹配限制为字符串的^开始和$结束。

演示:

http://plnkr.co/edit/7N0MQDYNWjo18bcmfIDB?p=preview

检查$scope.isActive方法返回的值

检查柱塞