2016-05-12 105 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()