【问题标题】:Require a json file within angularjs using nodejs使用nodejs在angularjs中需要一个json文件
【发布时间】:2014-04-01 04:07:14
【问题描述】:

我正在使用 NodeJS 和 AngularJS。

在 Angular 中,我想引用一个 json 文件并将 json 的各个部分分离到不同的控制器中。

目前我在控制器中使用 http.get(见下文)。

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

app.controller('introCtrl', function ($scope, $http) {
   $http.get('src/data_json.js').success(function(data) {
    $scope.intro = data;
});

这将返回我的第一个控制器中的整个 json 对象。但是我想需要 json 文件,将其存储为变量,并让多个控制器引用不同的部分。

有没有办法使用nodejs将json文件传递给angular控制器或者有没有更好的方法来使用angular来要求json文件?

非常感谢

【问题讨论】:

  • 在 Angular 应用程序中获得 json 后,您可以使用 Angular 服务将该 json 传递给其他控制器

标签: javascript json node.js angularjs


【解决方案1】:

一个好的策略是将http请求存储在服务Service中。然后,您只需注入该服务即可使所有控制器都可以使用该服务。

如果您使用REST 服务,您还应该考虑使用$resource

【讨论】:

    【解决方案2】:

    谢谢 - 我最终按照你的建议使用了工厂服务......

    var App = angular.module('App', []);
    
    // Setting up a service to house our json file so that it can be called by the controllers
    App.factory('service', function($http) {
        var promise;
        var jsondata = {
            get: function() {
                if ( !promise ) {
                    var promise =  $http.get('src/data_json.js').success(function(response) {
                        return response.data;
                    });
                    return promise;
                }
            }
        };
        return jsondata;
    });
    
    
    
    
    App.controller('introCtrl', function (service , $scope) {
        service.get().then(function(d) {
            $scope.header = d.data.PACKAGE.ITEM[0]
        })
    });
    
    App.controller('secondCtrl', function (service , $scope) {
        service.get().then(function(d) {
            $scope.title = d.data.PACKAGE.ITEM[1]
        })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2018-05-10
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      相关资源
      最近更新 更多