我已经将其添加到侧导航的控制器中:
if($location.path() == '/goals') {
$scope.goals_active = true;
}
这可以很好地工作,并使用ng-class
应用活动类。
然而,我现在遇到的问题是id。
即/goals/b2dcf461-56f6-f812-bed0-538e1603a595
在Angular中(如有必要,使用$location),我如何告诉我的应用程序,当路径为/goals
时,不仅要将$scope.goals_active
设置为true
,还要将/goals/:id
设置为?
我需要某种*
运算符,但不知道这怎么可能。
只需使用Regex:
//goals(/.*)?/.test($location.path());
下面是一个显示测试代码的快速片段:
var urls = ['/goals', '/goals/', '/goals/12345'];
urls.forEach(function(url){
var matches = //goals(/.*)?/.test(url);
document.write("url: " + url + " [" + matches + "]");
document.write("<br />");
});
if($location.path().indexOf("/goals") >= 0)
应该匹配其中包含/targels的任何内容。
如果你认为你不会有像/goalsSomething
这样的URL,而不应该触发,你可以简单地执行:
if($location.path().match('/goals')) {
$scope.goals_active = true;
}
或者斯科特的建议。
最安全的方法可能是使用正则表达式:
if( //goals(/.*)?/.test($location.path()) ) { $scope.goals_active = true; }
您也可以使用indexOf,但当您体验到带有诸如"/goolsadf"之类附加文本的路线时,这会变得更加复杂。还有许多其他方法可以做到这一点,而且越来越复杂。