在我的应用程序中,我有一个搜索页面,根据用户的查询加载数据。每个结果(波形为10)都有两个我想要动态切换的字段:“imgs”和“smallImgs”。
简而言之,如果结果是smallImgs.length == true
,那么我想加载这些图像。如果它没有长度,那么我想加载其imgs
。
我知道ng-hide
和ng-show
,我可以在模板中执行一个简单的true / false语句来显示或隐藏imgs
/ smallImgs
。但据我所知,即使我在一个元素上启用了ng-hide
,它仍会加载到该数据中(因此会将图像下载到客户端)。
我想到实现这一目标的唯一方法是在我的控制器中,在$resource
电话上抓取我的数据:
$scope.itemSearch.get({query:$routeParams.query, page:$routeParams.page}, function(data){
$scope.posts = data.posts;
for(var i = 0; i<$scope.posts.length; i++){
$scope.posts[i].imgs = testImgs($scope.posts[i]);
}
});
var testImgs = function(data){
if (data.smallImgs.length){
return data.smallImgs;
} else{
return data.imgs;
}
}
不幸的是我还没有完成这项工作。这是实现这一目标的最佳方式吗?在视图中是否有一种Angular方式来处理这个问题?
答案 0 :(得分:1)
我要做的是为控制器添加一个方法:
$scope.getImages = function () {
// add the logic to get the correct array here
};
然后在视图中使用它,例如
<div ng-repeat="image in getImages()" />
这是一个example jsfiddle。
答案 1 :(得分:0)
$ scope.itemSearch.get({query:$ routeParams.query,page:$ routeParams.page}) - 如果这返回了承诺,你可以这样做
$scope.getImages = $scope.itemSearch.get({query:$routeParams.query, page:$routeParams.page});
<div ng-repeat="image in getImages" />