简体   繁体   English

AngularJS http.get()访问json中断控制器

[英]AngularJS http.get() accessing json breaks controller

I'm new to AngularJS and have been trying to parse a json using the $http method. 我是AngularJS新手,并一直在尝试使用$http方法解析json I made a test $scope.test = "working"; variable 我做了一个测试$scope.test = "working"; variable $scope.test = "working"; variable , which works fine. $scope.test = "working"; variable ,可以正常工作。 After putting in my $http method code it stops working and the $http method isn't working either. 放入我的$http方法代码后,它停止工作,并且$http方法也不起作用。 Here is my json : 这是我的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"
      }
   ]
}

and here is my controller file: 这是我的控制器文件:

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

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

}]);

and finally, my html: 最后,我的html:

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

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

so with the $http.get() in the controller, {{test}} shows up literally, but when I remove it, it shows 'works'. 因此在控制器中使用$http.get()时, {{test}}字面显示,但是当我删除它时,它会显示“作品”。 The ng-repeat ul doesn't work at all. ng-repeat ul根本不起作用。 What am I doing wrong? 我究竟做错了什么?

You need to inject the $http angular service in your controller. 您需要在控制器中注入$ http角度服务。 You can take a look at your browser console. 您可以看一下浏览器控制台。 Generally it gives you a hint on what you missed. 通常,它给您提示您错过了什么。

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

You're seeing the angular expression {{test}} because your missing dependency breaks your controller code. 您正在看到角度表达式{{test}}因为缺少相关性会破坏控制器代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM