我正在表演 $http
向 500px API 请求一组流行照片。响应对象已成功返回,但我无法将返回的照片项推送到 View 。
我的 Controller 代码如下所示:
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
,但这也没有给我任何运气。
最佳答案
更新
问题是您的 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
的值。
作为一种解决方案,您可以将整个“照片搜索”部分(包括搜索和结果)包装在一个 Controller 的范围内。
您可能还必须考虑我之前的回复......
之前的回复
似乎在响应您的请求后,将结果作为数组推送到 $scope.photos
,其内容可能如下所示:
[{ current_page: ..., photos: [...], total_items: ..., totalpages: ...}]
如果是这种情况,您需要使用如下所示的表达式访问它:
<li ng-repeat="photo in photos[0].photos">
也许你真的想将数据分配给 $scope.photos
就像
$scope.photos = data
在这种情况下,您的表达式可能会像您当前那样工作。
关于javascript - AngularJS $scope.push 不从 $http 数据响应更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23840315/