Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS在html5路由更改中添加活动类_Javascript_Angularjs - Fatal编程技术网

Javascript AngularJS在html5路由更改中添加活动类

Javascript AngularJS在html5路由更改中添加活动类,javascript,angularjs,Javascript,Angularjs,我正在使用指令向菜单中的项目添加活动类。在我改用html5路由之前,它工作得很好。现在它不起作用了 这是指令的代码 app.directive('siteNavbar', ['$location', function($location) { return { restrict: 'A', templateUrl: 'partials/tpl/site-navbar.html', link: function (scope, elem) {

我正在使用指令向菜单中的项目添加活动类。在我改用html5路由之前,它工作得很好。现在它不起作用了

这是指令的代码

app.directive('siteNavbar', ['$location', function($location) {
    return {
      restrict: 'A',
      templateUrl: 'partials/tpl/site-navbar.html',
      link: function (scope, elem) {
        //after the route has changed
        scope.$on("$routeChangeSuccess", function () {
          var hrefs = ['/#' + $location.path(),
            '#' + $location.path(),
            $location.path()];
          angular.forEach(elem.find('a'), function (a) {
            a = angular.element(a);
            if (-1 !== hrefs.indexOf(a.attr('href'))) {
              a.parent().addClass('active');
            } else {
              a.parent().removeClass('active');   
            };
          });     
        });
        $(document).on('click.nav','.navbar-collapse.in',function(e) {
          if( $(e.target).is('a') ) {
            $(this).removeClass('in').addClass('collapse');
          }
        });
      }
    };
}]);
我相信问题出在代码的这一部分

var hrefs = ['/#' + $location.path(),
  '#' + $location.path(),
  $location.path()];

但我不知道如何更改它以使其工作,实际上我不确定它以前工作的原因。

可能是console.loga.attr'href',a=angular.elementa之后的$location.path;为了调试,发生了什么。我以前没有处理过这个问题,但是HTML5路由的全部目的不是为了摆脱路由中的//吗?因此,您现在可能只需要hrefs数组中的$location.path。之后会发生的事情是迭代页面上的每个标记,如果元素href为$location.path,则添加活动类,否则删除该类。您需要告诉我们您的某些链接是什么样子的,以及从$location.path返回的内容。我的链接看起来就像这样:@RyanS通过将它们更改为$location.path matched a.attr'href'如果您将您的建议作为答案发布,我会选择它。@JaredWhipple嘿,刚才我看到了一个很棒的建议。我一直在做同样的事情,直到我发现。我可以做一些事情,比如对我的项目应用.active类。还有无数其他令人敬畏的东西。我强烈建议你放弃这个指令,利用ui路由器。一旦你掌握了窍门,你会感谢自己的