ng-repeat不显示行

Lak*_*aka 0 javascript angularjs

我正在尝试学习AngularJS并开始我的第一个代码示例来获取用户的github repos.

我的html页面是这样的:

<!DOCTYPE html>
<html ng-app="githubViewer">

  <head>
    <link  rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="gitHubRepoController">
    {{error}}
    <table class="table table-striped">
      <thead>
        <tr>
        <th>Name</th>
        <th>Full Name</th>
        <th>HTML Url</th>
        <th>Description</th>
        </tr>
        </thead>
      <tbody>
        <tr ng-repeat="repo in repos">
          <td>{{repo.name}}</td>
          <td>{{repo.full_name}}</td>
          <td>{{repo.html_url}}</td>
          <td>{{repo.description}}</td>
        </tr>
      </tbody>
    </table>
  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

我的控制器是这样的

(function() {
  var app = angular.module("githubViewer",[]);

  var gitHubRepoController = function($scope, $http){
    $http.get("https://api.github.com/users/lakshman553/repos")
         .then(onDataDownloaded, onError);

  var onDataDownloaded = function(response) {
    console.log(response.data);
    $scope.repos = response.data;

  };
  $scope.error = "some value";
  var onError = function(reason) {
    $scope.error = reason;
  };
  };

  app.controller("gitHubRepoController",gitHubRepoController);
})();
Run Code Online (Sandbox Code Playgroud)

AngularJS被加载,因为它{{error}}显示在屏幕上显示为some value

表头已正确加载但未显示任何其他内容.当在broswer中看到时,甚至网址都会返回数据.

控制台中也没有错误.

我哪里错了?

k-n*_*nut 5

您需要在尝试使用它们之前将声明处理程序(onDataDownloaded,onErro)的声明移动到它.Plnkr

(function() {
  console.log('this is the app')
  var app = angular.module("githubViewer",[]);

  var gitHubRepoController = function($scope, $http){  
    var onDataDownloaded = function(response) {
      $scope.repos = response.data;
    };
    var onError = function(reason) {
      $scope.error = reason;
    };
    $http.get("https://api.github.com/users/lakshman553/repos")
    .then(onDataDownloaded, onError);
  };

  app.controller("gitHubRepoController",gitHubRepoController);
})();
Run Code Online (Sandbox Code Playgroud)

  • 另一种解决方案是使用函数声明而不是函数语句.function onError(reason){...}而不是var onError = function(reason){...};.提升导致后者在调用$ http.get时使用的点处未定义onError.有关吊装的详细解释,请访问http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092. (2认同)