根据查询参数设置angularjs常量

时间:2015-05-13 09:29:08

标签: javascript angularjs

我有角度常量,指向webservice终点

angular.module('myModule').constant('ws_url', 'http://localhost:9000')

我想将ws_url作为查询参数传递,并将常量值设置为该值。

因此,如果我将服务器称为http://localhost?ws_url=localhost:8000,则应将常量设置为loclahost:8000而不是默认值。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果您想设置查询参数,并且想要在所有其他控制器上访问该值,那么不要使用$rootScope,而是更好地选择factoryservice如下所示

如果您想提供静态网址,请使用

var searchQueryParams = $location.url('http://localhost?ws_url=localhost:8000'); 
searchQueryParams.$$search.ws_url; // gives you the ws_url query param value

如果您想获取动态网址,请使用

var searchQueryParams = $location.search();
searchQueryParams.ws_url  // gives you the ws_url query param value if url is http://localhost?ws_url=localhost:8000

<强> Working Demo

<强> HTML

<div ng-app='myApp'>
    <div ng-controller="ControllerOne"></div>
    <div ng-controller="ControllerTwo"></div>
</div> 

<强>脚本

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($location, WebServiceValues) {
    var searchQueryParams = $location.url('http://localhost?ws_url=localhost:8000'); 
    WebServiceValues.setUrlParam(searchQueryParams.$$search.ws_url);
    console.log('ControllerOne getUrlParam:',WebServiceValues.getUrlParam())
});

app.controller('ControllerTwo', function (WebServiceValues) {
    console.log('ControllerTwo getUrlParam:',WebServiceValues.getUrlParam())
});

app.factory('WebServiceValues', function () {
    var webServiceUrlParam
    return {
        setUrlParam: function (urlParam) {
            webServiceUrlParam = urlParam;
        },
        getUrlParam: function () {
            return webServiceUrlParam;
        }
    };
});