0

当我更改页面并使用 location.path() 或其他东西来获取相关的 URL 片段时,我想更改元素的类。

我正在使用 $routeProvider 进行路由。小提琴没有正确显示它,但它在我的代码中运行良好。我遇到的问题是当我加载下一页时它没有更新。

此代码获取我想要的 url 片段:

$scope.locationPath = $location.path().replace(/^\/([^\/]*).*$/, '$1');

这是一个非常简单的 JSfiddle:http: //jsfiddle.net/timothybone/kmBXv/1/

4

3 回答 3

2

will的答案几乎是正确的;您必须包装$location.path()一个函数,以便在每个摘要上执行它,而不仅仅是一次:

$scope.$watch(function () {
  return $location.path();
}, function() {
  return $location.path().replace(/^\/([^\/]*).*$/, '$1');
});

工作小提琴:http: //jsfiddle.net/kmBXv/3/

于 2012-11-20T07:04:37.747 回答
0

使用 $watch 的替代方法:

<li ng-class="{active:isActiveRoute('edit')}">edit</li>
<li ng-class="{active:isActiveRoute('list')}">list</li>

然后在你的控制器中:

$scope.isActiveRoute = function(route) {
   // I added '/' instead of using a regex to remove it from path()
   return '/' + route === $location.path();
};

另请参阅AngularJs: stateful client-side routing,它有一个工作小提琴。

于 2012-11-20T18:20:07.340 回答
0

这样的事情怎么样?

$scope.$watch($location.path(), function() {
  return $location.path().replace(/^\/([^\/]*).*$/, '$1');
}
于 2012-11-20T02:37:49.297 回答