在angularJS中,如何从属性文件中读取值?
connection.properties:
url="http://localhost:8080"
user= "me"
get= "GET"
post= "POST"app.js:
var app = angular.module('testing',[]);
app.controller('testCtrl',function($scope,$http) {
$http({
url: connection.properties.url ,
method: connection.properties.get,
params: {user: connection.properties.user})
});
});发布于 2013-10-01 01:32:14
如果connection.properties是一个驻留在web服务器上的文件,那么您只需执行以下操作:
var app = angular.module('app', []);
app.controller('test', function ($scope, $http) {
$http.get('connection.properties').then(function (response) {
console.log('a is ', response.data.a);
console.log('b is ', response.data.b);
});
});你可以在这里看到一个例子:
发布于 2016-06-07 19:05:48
简单的方法是
"config.js“(假设路径为scripts/config/config.js)
config.js:
var test2="globalconstant"
MainController.js:$scope.appUrl = test1;$scope.appConstant = test2;
发布于 2019-01-07 19:16:32
Langdon的回答为我加载了属性文件的内容,但是属性中的值以response.data.a和response.data.b等格式对我是不可访问的,并且总是返回undefined。为了使值对我可用,我必须提取属性文件的内容并将其转换为JSON格式,然后才能使用它。上述提议的解决方案的修改将是这样的:
var app = angular.module('app', []);
app.controller('test', function ($scope, $http) {
function extractProperties(data){
const lines = data.split("\n");
properties = {}
for (const l of lines) {
const line = l.trim();
if (!line || line[0] === '#') {
continue;
}
const keyValue = line.split("=");
const key = keyValue[0].trim();
const value = keyValue[1].trim();
properties[key] = value
}
return properties;
}
$http.get('connection.properties').then(function (response) {
const properties = extractProperties(response.data);
console.log('URL is ', properties.url);
console.log('User is ', properties.user);
});
});https://stackoverflow.com/questions/19100225
复制相似问题