11

在 angularJS 中,如何从属性文件中读取值?

connection.properties:  

url="http://localhost:8080"  
user= "me"  
get= "GET"  
post= "POST"

应用程序.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})        
     });
});
4

3 回答 3

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);
  });
});

你可以在这里看到一个例子:

http://plnkr.co/edit/3Ne3roFOwcfVmg2mgnUr?p=preview

于 2013-09-30T17:32:13.507 回答
2

简单的方法是

  1. 创建一个名为的js文件

    “config.js”(假设在路径 scripts/config/config.js 中)

    配置.js:

    var test1="http://testurl.com" var test2="globalconstant"

  2. 在 html 页面的顶部(在主 controller.js 上方)包含此 config.js:**<script.. src="./scripts/config/config.js"></st>**

  3. 在控制器中进行以下更改:

    MainController.js: $scope.appUrl = test1; $scope.appConstant = test2;

于 2016-06-07T11:05:48.073 回答
0

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);
    });
});
于 2019-01-07T11:16:31.560 回答