访问json的AngularJS http.get()打破了控制器

时间:2015-11-18 13:37:04

标签: javascript json angularjs

我是AngularJS的新用户,并尝试使用json方法解析$http。我做了一个测试$scope.test = "working"; variable,效果很好。在输入我的$http方法代码后,它停止工作,$http方法也无法正常工作。这是我的json

{
   "programmes":[
      {
         "@attributes":{
            "id":"1"
         },
         "name":"Arrow",
         "imagepath":"..\/img\/arrow.jpg"
      },
      {
         "@attributes":{
            "id":"2"
         },
         "name":"Fargo",
         "imagepath":"..\/img\/fargo.jpg"
      },
      {
         "@attributes":{
            "id":"3"
         },
         "name":"You, me and the Apocalypse",
         "imagepath":"..\/img\/youme.jpg"
      },
      {
         "@attributes":{
            "id":"4"
         },
         "name":"Heat",
         "imagepath":"..\/img\/heat.jpg"
      },
      {
         "@attributes":{
            "id":"5"
         },
         "name":"The Thick of It",
         "imagepath":"..\/img\/thick.jpg"
      }
   ]
}

这是我的控制器文件:

app.controller('MainController', ['$scope', function($scope) {
    $scope.test = "works";

    $http.get("../../jsons/programmes.json").success(function(response) {$scope.programmes = response.programmes;});

}]);

最后,我的html:

<ul>
  <li ng-repeat="x in programmes">
    {{ x.name }}
  </li>
</ul>

<p>{{test}}</p>

因此,对于控制器中的$http.get(){{test}}按字面显示,但当我删除它时,它会显示&#39;工作&#39;。 ng-repeat ul根本不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:5)

您需要在控制器中注入$ http角度服务。 您可以查看浏览器控制台。一般来说,它会给你一个你错过的提示。

app.controller('MainController', ['$scope', '$http', function ($scope, $http) {

您正在看到角度表达式{{test}},因为您缺少的依赖项会破坏您的控制器代码。