gpt4 book ai didi

javascript - 如何在 Angular View 中显示返回的 json?

转载 作者:行者123 更新时间:2023-11-27 23:22:24 24 4
gpt4 key购买 nike

我正在 github 存储库中执行搜索。我需要显示我从这里获得的信息:https://api.github.com/search/repositories?q=bootstrap .例如进入 View 或 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 上为空,但在控制台上不为空。

提前致谢结果为空

最佳答案

问题是,Angular 没有注意到 GitHub 服务器已经响应并且没有更新 View 。你必须手动告诉 Angular 重新渲染 View 。尝试调用 $scope.$apply():

github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data;
$scope.$apply();
});

如果您使用 Angulars $http 服务向 GitHub API 发出请求,则不需要 - 您只需要 $scope.$apply() 如果发生不存在于“Angular 世界”中的异步事件 - 例如 setTimeout、jQuery ajax 调用等。这就是为什么会有像 $timeout$http 这样的 Angular 包装器。

更多详情:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

关于javascript - 如何在 Angular View 中显示返回的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452229/

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