javascript - 将 JSON 文件导入运行在 Grunt 服务器上的 Angular 应用程序

标签 javascript json node.js angularjs gruntjs

我正在学习基本的 Angular 教程,需要在其中包含一个 JSON 文件。 我用 Yeoman 启动了我的应用程序,它正在运行。

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

phonecatApp.controller('PhoneListCtrl', function PhoneListCtrl($scope) {

  $http.get('phones/phones.json').success(function(data) {
    $scope.phones = data;
  });

});

但是,当我访问 localhost:9000 时,出现了一堆控制台错误:

ReferenceError: $http is not defined
    at new PhoneListCtrl (http://localhost:9000/scripts/controllers/main.js:17:3)
    at invoke (http://localhost:9000/bower_components/angular/angular.js:3000:28)
    at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:3012:23)
    at http://localhost:9000/bower_components/angular/angular.js:4981:24
    at http://localhost:9000/bower_components/angular/angular.js:4560:17
    at forEach (http://localhost:9000/bower_components/angular/angular.js:137:20)
    at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:4545:11)
    at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:4191:15)
    at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:4194:13)
    at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:4096:30) 

如有任何帮助,我们将不胜感激!

最佳答案

最好将 json 文件包含在工厂服务中。这样你就可以缓存它并继续在不同的 Controller 上使用它。

我遇到了类似的问题,然后就这样解决了...

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]
    })
});

关于javascript - 将 JSON 文件导入运行在 Grunt 服务器上的 Angular 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19278518/

相关文章:

javascript - 如何通过 Postman 将 JSON 发送到 NodeJS Express Server?

javascript - 反向图像搜索特定网站

node.js - npm 链接的本地库需要 node_modules 而 git 链接的库(相同)不需要

javascript - 通过背景颜色区分不同的结果

javascript - 为什么谷歌闭包编译器会警告数组的长度?

c# - 排除没有数据的对象

javascript - 使用 .animate() 跳转到 div

node.js - NodeJs/WS : How to throw an error server side handled on client side?

iPad 上的 Javascript 加载缓慢

php - 是否可以使用 javascript 弹出窗口接受 php 中的输入