9

I used to work with RequireJS and Backbone and used requirejs/text and requirejs-plugins to load local json files I normally use for configuration.

How does one achieve the same with AngularJS?

Everyone seems to suggest to use $http, but is this the only way? Do I really need to make 20 calls if I have 20 configuration files?

Maybe something like ng-constant is the "preferred" way?

2
  • 20 configuration files!? That's a lot of config! Commented Feb 5, 2014 at 22:08
  • Yeah. Oh well it's mainly labels and stuff like that or like a long list of (fixed) exchange rates. Commented Feb 5, 2014 at 22:20

3 Answers 3

8

This is what I did. But it uses $http though so I'm hoping someone has a better solution.

app.js:

var myModule = angular.module('myApp', []);

myModule.config(function($routeProvider, $locationProvider) {
    $routeProvider.when('/', {
        templateUrl: 'html/home.html',
        controller: 'MainCtrl as ctrl',
        resolve: {
            initializeData: function($q, $timeout, myService) {
                return myService.promiseToHaveData();
            }
        }
    });
});

myService.js:

var myModule = angular.module('myApp');

myModule.service('myService', function($http, $q) {
    var _this = this;

    this.promiseToHaveData = function() {
        var defer = $q.defer();

        $http.get('someFile.json')
            .success(function(data) {
                angular.extend(_this, data);
                defer.resolve();
            })
            .error(function() {
                defer.reject('could not find someFile.json');
            });

        return defer.promise;
    }
});

Then I can inject myService anywhere and it will have all the fields from the json file.

I guess alternatively you could just make your .json files .js files, have them expose a global variable, and reference them in your index.html

Sign up to request clarification or add additional context in comments.

Comments

7

Can you use jQuery's getJSON function?

E.g something like:

$.getJSON("config-1.json", function( data ) {
    // do whatever you want
});

Comments

2

Here's an AngularJs service that uses the FileReader API:

http://odetocode.com/blogs/scott/archive/2013/07/03/building-a-filereader-service-for-angularjs-the-service.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.