它的作用是接受“Github 用户名”的输入并使用它来显示其他值。它访问 API 并在名为“用户”的变量中捕获响应。我想要的是,当我输入一个不存在的用户名时,它应该显示“表格”、“错误”和 UI 的其他一些部分。当我输入有效的用户名时,它应该再次隐藏这些部分。
基本上,我希望能够在 ng-show 和 ng-hide 之间切换。我知道解决方案将非常简单,但我的大脑已经关闭,我花了最后 3 个小时尝试不同的排列,但都失败了。
继续解决..以免我会对此做噩梦,从字面上看。这段代码已经困扰着我了。
干杯!
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1><div>
<h1 ng-show="user">{{ message }}</h1>
</div></h1>
<div ng-show="username">
User handle: {{ username }}</div><br/>
<div ng-show="user">{{ error }}</div>
<form name="searchUser">
<input type = "search" placeholder = "username to find" ng-model="username">
<input type="submit" value = "Search" ng-click="search(username)">
Order: <select ng-model="repoSortSelector" ng-show="user">
<option value="+name">Name</option>
<option value="-stargazers_count">Star</option>
<option value="+language">Language</option>
</select>
</form>
<h2>{{ user.login }}</h2>
<img ng-src="{{ user.avatar_url }}" title="{{ user.login }}">
<table ng-show="user">
<thead>
<tr>
<th>Name</th>
<th>Language</th>
<th>Stars</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | orderBy: repoSortSelector">
<td>{{ repo.name }}</td>
<td>{{ repo.stargazers_count | number }}</td>
<td>{{ repo.language }}</td>
</tr>
</tbody>
</table>
</body>
</html>
和脚本
var app = angular.module('myApp', ['controllers']);
angular.module('controllers', []).controller('MainController', function($scope, $http) {
$scope.message = "Search User"
var onComplete = function(response) {
$scope.user = response.data;
if(user.message=="Not Found"){
$scope.user=0;
}
$http.get($scope.user.repos_url)
.then(onRepos, onReposError)
};
var onRepos = function(response) {
$scope.repos = response.data;
console.log($scope.repos);
$scope.repoSortSelector = "-stargazers_count";
}
var onReposError = function(reason) {
console.log(reason);
}
var onError = function(reason) {
$scope.error = "Could not find the result. Please try something else! "
}
// $scope.message = "Hello, Angular!"
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onComplete, onError);
}
});