Saturday, November 18, 2017

How to pass web configuraition value to angular controller/service via angular constant

In my appliction, there are few constant value need to pass the angular controllers . So I need to create angular constant and inject it everyware. So I have done the following steps to achived this,

Create the dynaic java script file .

01. In my case some of constant values has to fetch from the web config file. So I have create mvc conroller and return dynamically generated java scripts file when page is loading 

Asp.net Mvc Controller 

 public class ScriptsController : Controller
    {
        public ActionResult Constants()
        {
            var script = new StringBuilder();
            script.Append("(function () {");
            script.Append("angular.module('app')");
            script.Append(".constant('Settings', {");
            script.AppendFormat("AppUrl: '{0}',", ConfigurationManager.AppSettings["AppUrl"]);
            script.Append("});");
            script.Append("})();");
            return JavaScript(script.ToString());
        }
    }

In layout page call the url and load the dynamic java scripts file 

 "script type="text/javascript" src="@Url.Action("Constants", "Scripts")"

setting file is available to used everyware to used 

---settings file is injected and used web confile value inside java scripts controller. 

var app = angular.module('app', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider, Settings) {

    var baseUrl = Settings.AppUrl;

    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/About',
            templateUrl: baseUrl+ '/Home/About'
        })
        .state('Contact', {
            url: '/Contact',
            templateUrl: baseUrl + '/Home/Contact' 
        })
   // $locationProvider.hashPrefix('!').html5Mode(true);
});








No comments:

Post a Comment