Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 读取AngularJS中的本地文件_Json_Angularjs_Requirejs Text - Fatal编程技术网

Json 读取AngularJS中的本地文件

Json 读取AngularJS中的本地文件,json,angularjs,requirejs-text,Json,Angularjs,Requirejs Text,我曾经使用RequireJS和主干网,并使用和加载我通常用于配置的本地json文件 如何使用AngularJS实现同样的效果 每个人似乎都建议使用$http,但这是唯一的方法吗? 如果我有20个配置文件,我真的需要打20个电话吗 也许这是“首选”方式?我就是这么做的。但是它使用了$http,所以我希望有人有更好的解决方案 app.js: var myModule = angular.module('myApp', []); myModule.config(function($routeProv

我曾经使用RequireJS和主干网,并使用和加载我通常用于配置的本地json文件

如何使用AngularJS实现同样的效果

每个人似乎都建议使用$http,但这是唯一的方法吗? 如果我有20个配置文件,我真的需要打20个电话吗


也许这是“首选”方式?

我就是这么做的。但是它使用了$http,所以我希望有人有更好的解决方案

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;
    }
});
然后我可以在任何地方注入myService,它将拥有json文件中的所有字段

我想你也可以把.json文件变成.js文件,让它们公开一个全局变量,然后在index.html中引用它们。你能使用jQuery的函数吗

例如:

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

下面是一个使用FileReader API的AngularJs服务:


20个配置文件!?这是一个很大的配置!是 啊哦,主要是标签之类的东西,或者像一长串(固定)汇率。