如何在AngularJS中使用ng-class仅在特定页面上向元素添加类

How to add class to an element only on certain page using ng-class in AngularJS?

本文关键字:元素 添加 AngularJS ng-class      更新时间:2023-09-26

这似乎是一个非常简单的问题。但我卡住了:

<div ng-class="if we're on '/certainpage' : some-class"></div>

我所需要的只是仅在我们在"/certainpage"上时才显示类。

您要查找的是$location.path()(如果您有一些查询字符串,例如 /certainpage?a=1,则$location.url()可能不起作用)。

<div ng-class="{'some-class': isOnCertainPage()}"></div>

然后在控制器中:

$scope.isOnCertainPage = function() {
    return $location.path() === "/certainpage";
};

使用 Angular 的位置:

https://docs.angularjs.org/api/ng/service/$location

var url = $location.url();

不要忘记将服务添加到您的指令中。

$scope.checkLocation() = function() {
  var url = $location.url();
  if (url = 'yourUrlToCheck')
    return true
  return false
}
.red {
 color : red; 
}
<div ng-class="{'red': checkLocation() }">Here is a div</div>