John Baxter John Baxter - 2 months ago 8
AngularJS Question

Adding configuration file to Angular 1 how should the file be structured in order to use it

I have been wanting to have a central place for a configuration file with angular 1.5.8 that I can use for switching from JSON file to localhost to dev server and various other things.


  1. I noticed $injector, but I don't know that it will help me https://docs.angularjs.org/api/auto/service/$injector



I was looking at this Stackoverflow page

How do I configure different environments in Angular.js?

So with the way my code is setup, I was not sure how to structure data in a
app.config.js
file that I was creating.

app.js

(function () {
"use strict";
//angular.module('app', ['angularUtils.directives.dirPagination']);

var app = angular.module("deviceManagement",
['angularUtils.directives.dirPagination',
'common.services',
'ui.router'//,
//'deviceResourceRest'
//'deviceResourceMock'

]);

app.config( //....
....


NEW app.config.js

??


One main Controller

(function () {
"use strict";

angular
.module("deviceManagement")
.constant('adfaf', 'blah')
.directive('modal', [dirTest])
.controller("DeviceDetailCtrl",
["$window", "$scope",
"$http",
"$stateParams",
"deviceService",
//"dataFactory",
//ModalService,
DeviceDetailCtrl]);


function DeviceDetailCtrl($window, $scope, $http, device, deviceService) {
var vm = this;
vm.device = device;

}
} ());



  1. Does injecting a .constant make any sense ? .constant('adfaf', 'blah') ..

  2. How do I really set values in the file and then reference them in my function?


Answer

For your code, yes you can explore config file, but you referenced

.constant('adfaf', 'blah')

In your app.js after ]); and before your app.config... enter a constant

app.constant("rootUrl", "http://www.example.com");

Then add a .factory and inject this rootUrl into your controller notice -- web

(function () {
"use strict";

angular
    .module("deviceManagement")
    .factory('web', function($http, rootUrl){   // NOTICE HERE
        return { rootUrl: rootUrl}  // NOTICE HERE
    })  // NOTICE HERE 
    .constant('adfaf', 'blah')  // NOTICE HERE
    .directive('modal', [dirTest])
    .controller("DeviceDetailCtrl",
        ["$window", 
        "$scope",
        "$http",
        "web",  // NOTICE HERE 
        "$stateParams",
        "deviceService",
        //"dataFactory",
        //ModalService,
        DeviceDetailCtrl]);

      //blah whatever 

Then your controller passes web in

function DeviceDetailCtrl($window, $scope, $http, web, device, deviceService) {

Set to $scope or whatever you want...

 $scope.rootUrl = web.rootUrl;
 console.log($scope.rootUrl);

You should see that URL in your dev tools output...

Comments