Read local file in AngularJS

独自空忆成欢 提交于 2019-11-28 07:45:54

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

Can you use jQuery's getJSON function?

E.g something like:

$.getJSON("config-1.json", function( data ) {
    // do whatever you want
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!