UI-Router ng-class =“$ state.includes('name')”不在指令中工作

时间:2015-02-18 10:07:33

标签: javascript angularjs angularjs-directive angular-ui-router ng-class

我想使用ui-router的abilitie来测试ng-class中的活动状态

如果我试试这个不起作用:

navTest.$inject = ["$compile", "$navbar", "$state"];
function navTest($compile, $navbar, $state) {
    var defaults = $navbar.defaults;

    var navTest = {
        restrict: 'E',
        template: '<nav class="navbar navbar-default" role="navigation">' +
            '<div class="container-fluid">' +
                '<div class="navbar-header">' +
                    '<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">' +
                        '<span class="sr-only">Toggle navigation</span>' +
                        '<span class="icon-bar"></span>' +
                        '<span class="icon-bar"></span>' +
                        '<span class="icon-bar"></span>' +
                    '</button>' +
                    '<a class="navbar-brand" href="#">Brand</a>' +
                '</div>' +
                '<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">' +
                    '<ul class="nav navbar-nav">' +
                        '<li data-ng-class="{active: $state.includes(\'user\')}"><a data-ui-sref="user.List">Link 1</a></li>' +
                        '<li data-ng-class="{active: $state.includes(\'technology\')}"><a data-ui-sref="technology.List">Link 2</a></li>' +
                    '</ul>' +
                '</div>' +
            '</div>' +
        '</nav>',   
        replace: true
    };
    return navTest; 
}    

现在,如果我添加一个函数来测试&#34;链接中的活动状态&#34;功能 (指令)和我替换:data-ng-class =&#34; {active:$ state.includes(\&#39; technology \&#39;)}&#34;通过 data-ng-class =&#34; {active:isActiveState(\&#39; technology \&#39;)}&#34;

link : function (scope, elem, attrs) {
    scope.isActiveState = function (name) {                 
        return $state.includes(name);
    };
}

一切正常但我不明白为什么因为这个功能完全一样?

3 个答案:

答案 0 :(得分:6)

这是范围之物,但您不想使用$rootScope;在您的link函数中添加以下内容应该足够了:

scope.$state = $state;

答案 1 :(得分:4)

那是因为$state不在你的范围内。我建议您在$state中添加scope的引用(使用链接功能)。如果您在某些地方可能需要$state,我建议您使用模块/应用程序的运行功能将其添加到$rootScope

angular
    .module('yourModule')
    .run([
        '$rootScope',
        '$state',
        function ($rootScope, $state) {
            $rootScope.$state = $state;
        }
    ]);

答案 2 :(得分:1)

您可以在模板中使用ui-router过滤器。

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#filters-1

在你的情况下:

ng-class="{ active: 'user' | includedByState }"