2016-05-12 103 views
0

我有一個簡單的html文件,使搜索Algolia並返回結果。我可以控制結果,但不能從視圖訪問$ scope.users。我怎樣才能在視圖中獲取$ scope.users。

這裏是我的app.js文件

var myApp = angular.module('myApp', []); 

    myApp.controller('usersController', function($scope) { 
     $scope.users = []; 

     var client = algoliasearch('my_app_id', 'my_app_key'); 
     var index = client.initIndex('getstarted_actors'); 

     index.search('john', function searchDone(err, content) { 
      $scope.users.push(content.hits); 
      console.log(content.hits); 
     }); 

    }); 

這裏是我的HTML視圖文件

<div class="results" ng-controller="usersController"> 
    <div ng-repeat="user in users"> 
     <h3>{{ user.name }}</h3> 
    </div> 
</div> 

注:在HTML標籤給出NG-應用= 「對myApp」 屬性。

+0

這看起來正確。 – ryanyuyu

+0

{{user}}打印什麼,我相信你沒有用戶的name屬性。 –

+0

Sintax看起來很老,嘗試* ng-controller =「usersController as user」* then * ng-repeat =「usr in user.users」* and * {{usr.name}} *,很明顯請確認您的$ scope.users .push()真的推動 – sbaaaang

回答

1

這是最有可能因爲你index.search呼叫沒有觸發角$digest週期 - 手動觸發一個與任何$apply$timeout

index.search('john', function searchDone(err, content) { 
    $scope.users.push(content.hits); 
    $scope.$apply(); 
}); 

$apply()可能拋出$digest already in progress錯誤 - 另一種方式與$timeout

myApp.controller('usersController', function($scope, $timeout) { 
    index.search('john', function searchDone(err, content) { 
     $timeout(function() { 
      $scope.users.push(content.hits); 
     }); 
    }); 
}); 
+0

'$ scope。$ evalAsync()'我會說:P而不是$ timeout – sbaaaang

+0

不需要'$ timeout',因爲它會調用'$ apply' https://docs.angularjs.org/api/ ng/service/$ timeout可以通過將'invokeApply'設置爲false來關閉(默認爲true) –

+0

我認爲$ scope.users.push()它並不真正推動。因爲當我安慰index.search function()之外的$ scope.users它的只是安慰空[]數組。我該怎麼辦? –

0

嘗試撥打$scope.$apply()更新您的綁定

index.search('john', function searchDone(err, content) { 
    $scope.users.push(content.hits); 
    console.log(content.hits); 
    $scope.$apply(); 
}); 
0

algoliasearch看起來並不像它的注入服務,因此不是本機的角度框架。嘗試撥打$scope.$apply()