gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:57:06 25 4
gpt4 key购买 nike

我是 AngularJS 的新手,所以我被这个小的Users应用程序困住了。

而不是在 Controller 内写入用户数据数组 - 就像我已经做过的 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>

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

更新:工作 fiddle HERE

最佳答案

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

这里您还没有发出任何http请求来检索数据。这里的 users 变量的作用域只是一个 字符串即

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


}]);

关于javascript - AngularJS:使用 jsonplaceholder.typicode.com 作为数据源不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com