Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

json - Read local file in AngularJS

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...