AngularJS $ scope.push不从$ http数据响应更新视图

时间:2014-05-24 01:10:21

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

我正在对500px API执行$http个请求,以获取一组热门照片。响应对象正在成功返回,我无法将返回的照片项目推送到视图中。

我的控制器代码如下所示:

meanApp.controller 'SearchController', ['$scope', '$http', 'Global', ($scope, $http, Global) ->

  $scope.global = Global
  $scope.photos = []

  $scope.submit = ->
    if $scope.text

      $http.get("https://api.500px.com/v1/photos?feature=popular").success (data) ->
        $scope.photos.push data

]

响应对象(作为JSON)看起来像这样(为了简洁而修剪):

{
  "current_page":1,
  "total_pages":1449,
  "total_items":7244,
  "photos":[
    {
      "id":58494612,
      "user_id":1795149,
      "name":"Van Gogh!!!!"
    },
    {
      "id":49566952,
      "user_id":1795149,
      "name":"Autumn touch!"
    },
    {
      "id":49527034,
      "user_id":2670757,
      "name":"Untitled"
    },
    {
      "id":39374598,
      "user_id":3669660,
      "name":"The Wild Cannot Be Tamed Nor The Rednecks in it! "
    },
    {
      "id":28303657,
      "user_id":2843749,
      "name":"Main road to go to the moon"
    }
  ]
}

我的观点如下:

<h1>Photo search</h1>

<form ng-submit="submit()" ng-controller="SearchController">
Enter text and hit enter:
  <input type="text" ng-model="text" name="text">
  <input type="submit" id="submit" value="Submit">
</form>

<ul>
  <li ng-repeat="photo in photos.photos">{{photo.name}}</li>
  <li ng-hide="photos.length">No photos</li>
</ul>

目前的行为是<ul>没有更新。预期的行为是photo项目推送到<li>。我读过有关可能需要使用$apply的内容,但这并没有给我带来任何好运。

2 个答案:

答案 0 :(得分:2)

更新

问题是您的ng-repeat超出了SearchController

的范围
<form ng-submit="submit()" ng-controller="SearchController">
Enter text and hit enter:
  <input type="text" ng-model="text" name="text">
  <input type="submit" id="submit" value="Submit">
</form> <!-- end SearchController -->

<ul>
  <!-- Outside of SearchController's scope -->
  <li ng-repeat="photo in photos.photos">{{photo.name}}</li> 
  <li ng-hide="photos.length">No photos</li>
</ul>

因此无法访问photos.photos的值。

作为一种解决方案,您可以在一个控制器的范围内包装整个“照片搜索”部分,包括搜索和结果。

Demo

您可能还需要考虑我之前的回复......

之前的回复

似乎在对您的请求的响应之后,通过将结果推送到$scope.photos作为数组,其内容可能如下所示:

[{ current_page: ..., photos: [...], total_items: ..., totalpages: ...}]

如果是这种情况,则需要使用如下表达式访问它:

<li ng-repeat="photo in photos[0].photos">

也许你真的有意将数据分配给$scope.photos,如

$scope.photos = data

在这种情况下,您的表达式可能会像您当前拥有它一样。

答案 1 :(得分:0)

首先确保您的响应可用作Javascript对象。 尝试

console.log(data);
console.log($scope.photos);

在$ http.get的success函数中,看看 data 是一个JavaScript对象还是一个对象数组(在浏览器的JS控制台中)。如果它显示为字符串,则需要JSON使用

解析响应
JSON.parse(response);

在推送到阵列之前。请注意,您要推送到$ scope.photos数组的内容必须是照片对象。 console.log($ scope.photos)应该显示对象数组。最后,在推送数据后,您需要运行

$scope.apply();