Ng-class - 当 URL 包含特定字符串时应用

Ng-class - apply when URL includes certain string of characters

我的控制器中有以下内容;

$scope.location = $location.absUrl();

这为我提供了正在查看的当前页面的完整 URL。在我的 HTML 中,如果 URL 包含某个参数,我想应用 class。

ng-class="{'location': location == }

我不太确定在 : 之后放什么来计算表达式。 url 可能包含一个字符串,例如 'requestId=555'

我如何编写一个表达式,以便在 URL 包含该字符串时应用 class?

如果您使用的是ui-router

您可以为查询字符串设置状态参数。如果你将 $stateParams 注入你的控制器,你可以访问集合 $scope.requestId = $stateParams.requestId。在您看来,您可以绑定到 requestId。设置状态:

$stateProvider.state({
    url: '/someurl?requestId',
    templateUrl: 'someTemplate.tpl.html',
    controller: 'SomeController'
});

ui-router

如果你想要普通的 js

根据这个广为接受的answer,可以通过以下函数获取某个键的查询字符串值:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
    var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

然后您可以设置 $scope.requestId = getParameterByName('requestId'); 并在您的模板中绑定它。