Ng-class - 当URL包含某些字符串时应用

时间:2015-12-03 19:16:03

标签: angularjs regex ng-class

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

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

这为我提供了当前正在浏览的网页的完整网址。在我的HTML中,如果URL包含某个参数,我想应用一个类。

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

我不确定在评估表达式之后要放什么。网址可以包含诸如< requestId = 555'

之类的字符串

如何编写表达式,以便在URL包含该字符串时,该类将被应用?

1 个答案:

答案 0 :(得分:1)

如果您使用的是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');并在模板中绑定它。