我有角度常量,指向webservice终点
angular.module('myModule').constant('ws_url', 'http://localhost:9000')
我想将ws_url作为查询参数传递,并将常量值设置为该值。
因此,如果我将服务器称为http://localhost?ws_url=localhost:8000
,则应将常量设置为loclahost:8000
而不是默认值。
我该怎么做?
答案 0 :(得分:1)
如果您想设置查询参数,并且想要在所有其他控制器上访问该值,那么不要使用$rootScope
,而是更好地选择factory
或service
如下所示
如果您想提供静态网址,请使用
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;
}
};
});