根据Angular中的路由更改添加Bootstrap活动类

时间:2017-04-12 08:59:33

标签: javascript angularjs ngroute

我正在尝试根据路径在导航菜单上使用Angular ngClass添加一个类(bootstrap活动类)。
navigationMain模板:

<div class="section">
<div class="container">
    <div class="row">
        <div class="col-md-12" ng-controller="MainCtrl">
            <ul class="nav nav-pills nav-justified" style="width:30%">
                <li ng-class="{active: location === '#!/home', nav-item}">
                    <a href="#!/home">Home</a>
                </li>
                <li ng-class="{active: location === '#!/resume', nav-item}">
                    <a href="#!/resume">CV</a>
                </li>
                <li ng-class="{active: location === '#!/overviewActivities', nav-item}">
                    <a href="#!/overviewActivities">I-Talent</a>
                </li>
            </ul>
        </div>
    </div>
</div>

app.module.js:

angular.
    module('iTalentApp', [
    'ngRoute',
    'home',
    'resume',
    'navigationMain'
]).controller('MainCtrl', function ($scope, $rootscope, $location) {
    $scope.location = $location.path();
    $rootScope.$on('$routeChangeSuccess', function () {
        $scope.location = $location.path();
    });
});

index.html:

<body>
    <navigation-main></navigation-main>
    <div ng-view></div>
  </body>

我的配置:

angular.
module('iTalentApp').
config(['$locationProvider', '$routeProvider',
    function config($locationProvider, $routeProvider) {
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/home', {
                template: '<home></home>'
            }).
            when('/resume', {
                template: '<resume></resume>'
            }).
            when('/overviewActivities', {
                template: '<overview-activities></overview-activities>'
            }).
            otherwise('/home');
    }
]);

我试图实现这个问题的解决方案adding or removing classes based on route changes in angular,但无济于事。谁能指出我做错了什么?

这正是我想要实现的,但是在一个带有角度的单个页面中,http://plnkr.co/edit/FNwIAU4OgQHlREIfi4BG我使用了它,除了条件活动类使用它们。 (我对html,css和js也很新)

修改 errormessage:

angular.js:14199 Error: [$injector:unpr] Unknown provider: $rootscopeProvider <- $rootscope <- MainCtrl
http://errors.angularjs.org/1.5.11/$injector/unpr?p0=%24rootscopeProvider%20%3C-%20%24rootscope%20%3C-%20MainCtrl
    at angular.js:68
    at angular.js:4563
    at Object.getService [as get] (angular.js:4716)
    at angular.js:4568
    at getService (angular.js:4716)
    at injectionArgs (angular.js:4741)
    at Object.invoke (angular.js:4763)
    at $controllerInit (angular.js:10592)
    at nodeLinkFn (angular.js:9469)
    at compositeLinkFn (angular.js:8810)

1 个答案:

答案 0 :(得分:0)

由于我们在评论中发现了错误,我会花时间写一个答案以供将来参考,问题是:
- 控制器中的拼写错误,将$ rootscope更改为$ rootScope,
- 错误使用ng-class语法,删除了nav-item - ng-class的表达错误,位置===&#39;#!/ path&#39;改为位置===&#39; / path&#39;。
感谢@dfsq