2016-11-06 61 views
2

我正在執行github存儲庫中的搜索。 我需要顯示我從這裏得到的信息:https://api.github.com/search/repositories?q=bootstrap。例如視圖或HTML如何在角度視圖中顯示返回的json?

<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: '[email protected]', 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空,但沒有在控制檯上空當。

提前感謝 結果是空

+1

沒有「JSON對象」這樣的事情。請閱讀'json'標籤的使用說明。 – trincot

+0

我的不好,我需要顯示我從搜索中獲得的信息。謝謝 – kuhle

回答

1

的問題是,角度不注意到GitHub的服務器已經回答不更新視圖。你必須手動告訴Angular重新渲染視圖。嘗試調用$scope.$apply()

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

如果你想使你的請求到GitHub的API與Angulars $http服務,那麼這將是不需要的 - 你只需要$scope.$apply()如果事情發生異步其犯規住在「 Angular world「 - 例如setTimeout,jQuery ajax調用等等。這就是爲什麼有像$timeout$http的角包裝。

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

+0

錯字,它的$範圍。$ apply(); – nmanikiran

+0

更新了我的答案,謝謝! –

+0

我嘗試了$ apply(),但我仍然得到一個空白。我認爲我的問題是,我無法獲得HTML文件的「userData」,因爲我從不同HTML文件的輸入中搜索。 – kuhle

0

既然你不使用的角$ http服務,棱角分明是不知道的變化。您需要手動告訴角度重新呈現,並通過使用

$scope.$apply(); 
1

GitHub的API評價可以使用AngularJS $http服務訪問:

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> 

DEMO on JSFiddle