AngularJS Edmunds REST API调用 - 加载下拉列表不起作用

时间:2014-09-12 21:14:01

标签: javascript angularjs api rest

我正在尝试查询Edmunds.com REST API,以便根据品牌和型号提取汽车。

在我的示例中,我只想ping他们的API以获取所有品牌并在下拉列表中显示它们。一旦你选择了一个make,我想得到一个make的所有模型的列表,并用它加载Models下拉列表。

我无法让它发挥作用。我在想我的carController有问题。我在Chrome调试器中看到的错误是“Argument'carController'不是函数,未定义”。我有carController但是因为它不喜欢它。 有人可以告诉我,我做错了什么?

以下是plunker: http://plnkr.co/edit/h0zAInSk1wIo0PRQNxGL?p=preview

//carController.js
    (function() {
  var app = angular.module('AngularSamples', []);

    var carController = function($scope, $http) {
      // get all the makes
        $http.get('https://api.edmunds.com/api/vehicle/v2/makes?state=new&view=basic&fmt=json&api_key=mexvxqeke9qmhhawsfy8j9qd')
        .then(function (response)
              {
                $scope.makes = response.data;
                }, function (error) {
                $scope.error1 = JSON.stringify(error);
                });

        // for each make - get all the models.
        $scope.getmodels = function(make) {
            $http.get('https://api.edmunds.com/api/vehicle/v2/"+make+"/models?state=new&view=basic&fmt=json&api_key=mexvxqeke9qmhhawsfy8j9qd')
        .then(function (response)
              {
                $scope.models = response.data;
                }, function (error) {
                $scope.error2 = JSON.stringify(error);
                });
        };

        app.controller('carController', ['$scope', '$http', carController]);
    };
})();

这是我试图点击并返回JSON的API链接: https://api.edmunds.com/api/vehicle/v2/makes?state=new&year=2014&view=basic&fmt=json&api_key=mexvxqeke9qmhhawsfy8j9qd

1 个答案:

答案 0 :(得分:1)

这实际上是一个简单的错误,当你看到错误时你会踢自己。交换这两行:

    app.controller('carController', ['$scope', '$http', carController]);
};

阅读:

};

app.controller('carController', ['$scope', '$http', carController]);

您将carController定义为上面示例顶部附近的var。但是你正试图从INSIDE本身使用它。您只需将此行代码移动到控制器外部即可。

顺便说一下,你的Plnkr因为一个额外的错误而无法正常工作,但我认为这只是一个剪切/粘贴问题 - 你要求js / carController.js但是在Plunkr中该文件是在顶级。

我在这个Plnkr中修了一两个小问题。 Makes选择器现在正在工作。模型不是,但这是因为API为您正在使用的查询返回一个空数组 - 我不知道这个API所以您需要检查网络请求并修复任何错误。

http://plnkr.co/edit/BGY76tIXhprPWgt5aphx?p=preview