在 AngularJS 中读取本地文件 [英] Read local file in AngularJS

查看:74
本文介绍了在 AngularJS 中读取本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经使用 RequireJS 和 Backbone 并使用过 requirejs/textrequirejs-plugins 加载我通常用于配置的本地 json 文件.

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.

如何使用 AngularJS 实现相同的效果?

How does one achieve the same with AngularJS?

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

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?

也许像 ng-constant 之类的东西是首选"方式?

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

推荐答案

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

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:

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 文件中的所有字段.

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

我想或者你可以让你的 .json 文件成为 .js 文件,让它们公开一个全局变量,并在你的 index.html 中引用它们

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

这篇关于在 AngularJS 中读取本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆