AngularJS Read Property File Using Service Controller
Here I will show you how to read value from property file using service and controller. We will use $http service to make call to the server from service and return response to the controller. Controller will process response object and put data inside the scope which we will use print on web page.
Tools needed:
- Eclipse Kepler ( You could use any version of eclipse now a days all eclipse comes with maven plug-in)
- Tomcat Server
- Maven
We will create small web application and deploy on tomcat server:
- Create maven web project name: JavaHonkAngularJSProperty
- Final project structure:
- Test.properties file:
{ "TestString": "Read value from file", "BooleanValue": false }
- HTML page:
<!DOCTYPE html> <html data-ng-app="serviceModule"> <head> <meta charset="ISO-8859-1"> <title>AngularJS Service example</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> <script type="text/javascript"> var serviceModule = angular.module('serviceModule', []); serviceModule.controller('myServiceController', function($scope, sampleService) { $scope.variable = "Read property value using service controller example" sampleService.getDataExample1().then(function(response){ $scope.TestStringValue = response.data.TestString; $scope.BooleanValue = response.data.BooleanValue; console.log($scope.TestStringValue); }); sampleService.getDataExample2().then(function(response){ $scope.TestStringValue = response.data.TestString; $scope.BooleanValue = response.data.BooleanValue; console.log($scope.TestStringValue); }); }); serviceModule.service('sampleService', function($http) { this.getDataExample1 = function() { var promise = $http({ method : 'GET', url : 'resources/Test.properties' }).success(function(data, status, headers, config) { return data; }); return promise; }; this.getDataExample2 = function() { var promise = $http.get('resources/Test.properties').success(function(data, status, headers, config) { return data; }); return promise; }; }); </script> </head> <body data-ng-controller="myServiceController"> <div> <h2>{{variable}}</h2> <p>1. String value: {{TestStringValue}}</p> <p>2. Boolean value: {{BooleanValue}}</p> </div> </body> </html>
- Run this project in tomcat you will see below output:
- For more information please use their official site here
Download Project: JavaHonkAngularJSProperty