What is the process of parsing a Java property file in AngularJS?

Is it possible to access a properties file from an AngularJS application that is located outside of the web server?

For example, in Java we can access a property file deployed separately from the project. Is there a way to achieve this in AngularJS?

I attempted to do this but I am receiving an 'undefined' result.

filter.properties:

key1=value1 
key2=value2

sampleController.js

var app = angular.module('sampleApp', []);
    app.controller('sampleController', function($scope, $http) {
    $http.get('filter.properties').then(function (response) {
        console.log('Value for key1 is ', JSON.stringify(response.data.key1));
    });
});

Answer №1

AngularJS provides various methods for accessing properties files.

A properties file, like any other file, has a .properties extension and consists of key-value pairs separated by an equal sign (=) on each line.

To convert a properties file into a JavaScript object, you can iterate through each line in the file, split it using the equal sign as a delimiter, and store the key-value pairs in a JavaScript object for quick access.

Here is an example of implementing this in JavaScript:

function extractProperties(propertiesFileContents){
  var keyValuePairs = propertiesFileContents.split("\n");
  var properties = {};
  for (var i = 0; i < keyValuePairs.length; i++) {
     var keyValueArr = keyValuePairs[i].trim().split("=");
     var key = keyValueArr[0];
     var value = keyValueArr[1];
     properties[key] = value;
  }
  return properties;
}

If you would like to see a live demonstration, you can check out this plunker. I hope this helps!

Answer №2

After testing Samuel J Mathew's solution and finding it effective, I encountered additional complexities in the properties file I was working with. This file contained multiple empty lines, commented-out lines, and white spaces around the "=" sign. To address these issues, I made some modifications to the code. The updated version is designed to handle these situations and may prove helpful for those dealing with more intricate properties files:

function processProperties(data){
    const keyValuePairs = data.split("\n");
    properties = {}

    for (var i = 0; i < keyValuePairs.length; i++) {
      const keyValuePair = keyValuePairs[i].trim();
      if (!keyValuePair || keyValuePair[0] === '#') {
        continue;
      }
      const keyValueArr = keyValuePair.split("=");
      const key = keyValueArr[0].trim();
      const value = keyValueArr[1].trim();
      properties[key] = value
    }

    return properties;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

Retrieve data from an HTML form and utilize it to search a JSON array for a specific value

If I have a Json File structured like this: {"403": [ { "403-01-01": "219,00" }, { "403-01-02": "180,00" } ], "404": [ { "404-01-01": "26,00" }, {"403-01-02": " ...

Grids designed in the style of Pinterest

Seeking advice on aligning divs in a Pinterest-style layout. Currently, my setup looks like this: https://i.sstatic.net/erlho.png But I want it to look more like this: https://i.sstatic.net/K9FnD.png Would greatly appreciate any tips or suggestions on ho ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

The Vue.js scripts and styles declared in the index.html file seem to be malfunctioning

I acquired a theme that includes html, css3, and js files, and I included the file path as shown below: <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Porto - Responsive HTML5 Te ...

What is the best way to retrieve the value of a checkbox element in React.js when submitting a form?

Whenever I try to submit a form, I encounter an issue where I am unable to retrieve the value of the checked boxes (I don't mean the check value but the actual value attribute of the HTML element). Here is an example of my element in the parent compo ...

One versatile service/module/library in Angular 1 that can be shared among several different "apps"

Trying to explain it as best I can: I currently have an angular app for one specific functionality. For example, I have a "campaigns" functionality that includes adding, editing, displaying all, and displaying in different ways. For the add and edit fun ...

The hover dropdown remains active even after the mouse has left

I've created a script for displaying a dropdown menu on small screens with a click (or tap on mobile), but I want it to change to hover when the screen size is larger. Here's my code: $(document).ready(function() { var open = false; ...

Guide to executing two child processes sequentially in Node JS

I am working on two processes within a function: one generates a JSON file from an audio while the other normalizes the generated JSON file. However, I'm facing an issue where only one of the processes runs at a time - when the first one runs, the se ...

Creating a callback in C code with Emscripten for JavaScript integration

In this challenge, the goal is to incorporate a JavaScript function as a callback to display progress during a while-loop operation. For example: var my_js_fn = function(curstate, maxstate){//int variables console.log(curstate.toString() + " of " + maxsta ...

Implement an autocomplete feature for input tags that are added dynamically

I am currently building an autocomplete feature for an input field using the code snippet below: $('.query').autocomplete({ serviceUrl:'http://localhost/main/finder.php', minChars:2, delimiter: /(,|;)\s*/, // regex or ...

Retrieve a result by utilizing a nested function in conjunction with the request NPM module

Hello there! I'm currently working on scraping data from the ghost blogging platform using the request package. However, I've run into a bit of a roadblock when trying to return a value of a nested request. I've pinpointed the area that seem ...

Transferring variables from the $(document).ready(function(){}) to the $(window).load(function(){} allows for seamless and

Just think about if I successfully create percent_pass at the time of document.ready, how can I transfer that variable to window.load? $(document).ready(function() { jQuery(function() { var ques_count = $('.question-body').length; va ...

Unexpected behavior with Angular directives

Looking for a way to achieve two-way binding in AngularJS directives with boolean values? Here's an example of a directive: var xmlToHtml = function () { return { restrict: "A", templateUrl: 'Components/XML2Html/views/XML2Htm ...

Display validation errors in Angular2 forms when the form items are left empty and the user tries to submit the form

In my application, I have a userForm group containing keys such as name, email, and phone. Additionally, there is an onValueChanged function that subscribes to changes in the form and validates the data. buildForm(): void { this.userForm = this.fb.gr ...

Guide to arranging components in two columns using VueJS Vuetify Grid

My goal is to align two components in order to display data on two columns. I followed the official Vuetify Grid tutorial, but encountered some issues with fixed row components. Despite trying to change from row to column, it still doesn't work as exp ...

Is it possible to maintain HTML, JS, and CSS files as separate entities when developing Vue.js components, similar to how it is

Is it possible to maintain separate HTML, JS, and CSS files while creating Vue.js components? I recently read the "Why Vue.js doesn't support templateURL" article which discusses this topic. "Proper modularization is a necessity if you want to bu ...

After executing "npm run dev" in Svelte and Vite, a common error message of "HTMLElement is not defined" might appear

Incorporating several web components into my Svelte project led to the appearance of an error message stating HTMLElement is not defined after running npm run dev (which actually translates to vite dev). The complete error message reads as follows: HTMLEl ...

Stopping the execution of code in Node.js after returning a JSON response

When a user is not found, the code still continues executing after sending the JSON response. The JSON response is generated in a separate class and returned from there. var user = new UserClass(obj, null); var userObj = user.getUser(res, req, 'user ...

Can the lib property in tsconfig.json override the target property?

Just starting out with Typescript, I have a query regarding the lib and target properties. Below is my tsconfig.json file: { "compilerOptions": { "target": "es5", "outDir": "./dist", "rootDir": "./src", "noEmitOnError": true, } } //index.ts consol ...