我正在尝试隐藏我在index.html中包含的HTML部分。现在发生的事情是当我搜索用户时,表格以及内容会在页面上呈现。我想要的行为是当按下“清除”时,包括HTML表及其内容被删除。现在,该表仅显示$ scope.user是否具有值,并且该检查是使用ng-if完成的。当我单击“清除”按钮时,我将$ scope.user设置为“false”,我认为这将删除包含。我也尝试将它添加到表DOM元素,但这也不起作用。我得不到什么?对于那些了解Angular的人来说,我确信这是一个相当简单的解决方案。
的index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{ message }}</h1>
<div>{{ error }}</div>
<form name="searchUser" ng-submit="search(username)">
<input type="search" required placeholder="Username..." ng-model="username" />
<input type="submit" value="Search" />
<button ng-click="clearSearch()">Clear</button>
</form>
<div ng-include="'userDetails.html'" ng-if="user"></div>
</body>
</html>
的script.js
(function() {
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
$http.get($scope.user.repos_url)
.then(onRepos, onError);
};
var onRepos = function(response) {
$scope.repos = response.data;
}
var onError = function(reason) {
$scope.error = "Could not fetch the data";
}
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
}
$scope.clearSearch = function() {
return ($scope.user = false);
}
$scope.message = "Github Viewer";
$scope.repoSortOrder = "+name";
};
app.controller("MainController", ["$scope", "$http", MainController])
}());
userDetail.html
<div>
<h2>{{ user.name }}</h2>
<img ng-src="http://www.gravatar.com/avatar/{{ user.gravatar_id }}" />
<h2>User Repositories</h2>
Order By:
<select ng-model="repoSortOrder">
<option value="+name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="+language">Language</option>
</select>
<table>
<thead>
<tr>
<th>Repository Name</th>
<th>Stars</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | orderBy:repoSortOrder">
<td><a href="{{ repo.html_url }}">{{ repo.name }}</a>
</td>
<td>{{ repo.stargazers_count | number }}</td>
<td>{{ repo.language }}</td>
</tr>
</tbody>
</table>
</div>
答案 0 :(得分:0)
我最终搞清楚了。 <问题是
<button ng-click="clearSearch()">Clear</button>
在<form>
,所以当我点击“清除”按钮时,搜索功能再次被执行。我通过Chrome控制台注意到这一点,因为我打开了XHR请求...当我点击“清除”时,正在执行另一个GET。
我将按钮移到<form>
之外,功能按预期工作。
答案 1 :(得分:-1)
clearSearch()应该设置$ scope.user的值而不是返回值:
$scope.clearSearch = function() {
$scope.user = false;
}