2

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

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) 

任何帮助,将不胜感激!

4

2 回答 2

5

It may be better for you to include the json file in a factory service. That way you can cache it and continue to use it with different controllers.

I had a similar issue and resolved it like so...

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]
    })
});
于 2014-03-02T13:05:39.783 回答
4

添加为依赖项,在您的$http旁边$scopefunction PhoneListCtrl($scope, $http) {}

于 2013-10-09T17:20:04.420 回答