我正在github存储库中实现搜索。 我需要显示从这里获得的信息:https://api.github.com/search/repositories?q=bootstrap。例如进入视图或HTML
<div ng-app="newsearchApp">
<div ng-controller="MainCtrl">
<form action="#/about" method="get">
<input ng-model="searchText" />
<button ng-click="search()">Search</button>
</form>
</div>
</div>
搜索Github存储库的代码;
angular.module('newsearchApp')
.controller("MainCtrl", ["$scope", function($scope) {
$scope.searchText = "";
$scope.search = function() {
console.log($scope.searchText);
var item = $scope.searchText;
// console.log(item)
var GithubSearcher = require('github-search-api');
var github = new GithubSearcher({username: 'test@something.com', password: 'passwordHere'});
var params = {
'term': $scope.searchText
};
//i am not certain about the 'userData'
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data; //i am not certain about the 'repoData'
});
} }]);
问题出在这里,将json对象填充到HTML
<div ng-repeat="repo in userData | filter:searchText | orderBy:predicate:reverse" class="list-group-item ">
<div class="row">
<div class="col-md-8">
<h4>
<small>
<span ng-if="repo.fork" class="octicon octicon-repo-forked"></span>
<span ng-if="!repo.fork" class="octicon octicon-repo"></span>
<small>{{repo.forks_count}}</small>
</small>
<a href="{{repo.html_url}}" target="_blank" >
{{repo.name}}
</a>
<small>{{repo.description}}</small>
<small>{{repo.stargazers_count}}</small>
<a href="{{repo.open_issues_count}}" target="_blank" >
Open Issues
</a>
<small>{{}}</small>
</h4>
</div>
</div>
</div>
HTML上的结果为null,但控制台上的结果不为null。
提前谢谢 结果为空答案 0 :(得分:1)
问题是,Angular没有注意到GitHub服务器已经回答并且没有更新视图。您必须手动告诉Angular重新渲染视图。尝试拨打$scope.$apply()
:
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data;
$scope.$apply();
});
如果您使用Angulars $http
服务向GitHub API发出请求,则不需要这样做 - 如果出现异步的情况,您只需要$scope.$apply()
生活在&#34; Angular世界&#34; - 例如setTimeout
,jQuery ajax调用等等。这就是为什么有像$timeout
和$http
这样的Angular包装器的原因。
更多详情:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
答案 1 :(得分:1)
可以使用AngularJS $http
服务访问GitHub API:
app.controller("myVm", function($scope,$http) {
var vm = $scope;
var url = "https://api.github.com/search/repositories?q=bootstrap"
$http.get(url).then(function onSuccess(response) {
vm.data = response.data;
console.log(vm.data);
})
})
HTML
<div ng-app="myApp" ng-controller="myVm">
<div ng-repeat="item in data.items">
{{item.full_name}}
</div>
</div>
答案 2 :(得分:0)
由于您没有使用Angular $ http服务,因此angular不知道更改。您需要手动告诉Angular使用
重新渲染和评估$scope.$apply();