AngularJS:使用JSONPLACEHOLDER.TYPICODE.com作为数据源不起作用



我是AngularJS的新手,因此我被这个小型用户应用程序所困。

而不是在控制器内写下用户数组 - 就像我在这里完成的(JSFIDDLE)一样,我想将JSONPLACEHOLDER.TYPICODE.com用作数据源:

var root = 'https://jsonplaceholder.typicode.com';
// Create an Angular module named "usersApp"
var app = angular.module("usersApp", []);
// Create controller for the "usersApp" module
app.controller("usersCtrl", ["$scope", function($scope) {
  $scope.users = root + "/users";
}]);
.search-box {
  margin: 5px;
}
.table-container .panel-body {
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container" data-ng-app="usersApp">
  <div class="panel panel-default table-container">
    <div class="panel-heading">Users</div>
    <div class="panel-body" data-ng-controller="usersCtrl">
      <div class="row">
        <div class="col-sm-12">
          <div class="form-group search-box">
            <input type="text" class="form-control" id="search" placeholder="Search User" data-ng-model="search">
          </div>
        </div>
        <div class="col-sm-12">
          <table class="table table-striped table-bordered" id="dataTable">
            <thead>
              <tr>
                <th>Full name</th>
                <th>Email</th>
                <th>City</th>
                <th>Street</th>
                <th>Suite</th>
                <th>Zipcode</th>
              </tr>
            </thead>
            <tbody>
              <tr data-ng-repeat="user in users|filter:search">
                <td>{{user.name}}</td>
                <td><a href="mailto:{{user.email}}">{{user.email}}</a></td>
                <td>{{user.address.city}}</td>
                <td>{{user.address.street}}</td>
                <td>{{user.address.suite}}</td>
                <td>{{user.address.zipcode}}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

但由于某种原因我无法理解,但它行不通。我究竟做错了什么?谢谢!

更新:工作小提琴在这里

 var root = 'https://jsonplaceholder.typicode.com'
    $scope.users = root + "/users";

在这里,您尚未提出任何HTTP请求来检索数据。在这里,用户范围中的变量只是一个 字符串即

 $scope.users =  'https://jsonplaceholder.typicode.com/users'

代码应该像这样

var root = 'https://jsonplaceholder.typicode.com';
// Create an Angular module named "usersApp"
var app = angular.module("usersApp", []);
// Create controller for the "usersApp" module
app.controller("usersCtrl", ["$scope","$http", function($scope,$http) {
  var url = root + "/users"
  // $http is a service in angular which is used to make REST calls
  // we call the url  and get the data , which is resolved as a promise
  $http.get(url)
 .then(function(data){
// after the data is resolved we set it in the scope
    $scope.users = data.data;
 })

}]);

最新更新