AngularJS:使用jsonplaceholder.typicode.com作为数据源不起作用

时间:2017-11-24 20:39:41

标签: javascript angularjs

我是AngularJS的新手,所以我遇到了这个小的 Users 应用程序。

而不是在控制器中写入用户数据数组 - 就像我已经完成HERE(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>
&#13;
&#13;
&#13;

但它不起作用,由于某些原因我无法理解。我究竟做错了什么?谢谢!

更新:工作小提琴 HERE

1 个答案:

答案 0 :(得分:0)

 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;
 })


}]);