gpt4 book ai didi

javascript - 我可以保留范围的旧值并将其他值更新为 AngualrJS 中的其他 div

转载 作者:行者123 更新时间:2023-12-02 15:07:20 25 4
gpt4 key购买 nike

好吧,我将尝试解释我这样做的方法。为了简单起见,我 trim 了代码。我想在应该有 <h4>BroadCategory Name</h4> 的地方创建一个 div在此标题下方,我调用一个 API 来获取与该 BroadCategory Name

关联的一些图像
  <div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>

<div ng-init="getImgForCategory(this.primaryItems)">
<div ng-repeat="ad in ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</div>
</div>
</div>

我的 Controller :

$http.get("/get_categories/")
.success(function(response){
$scope.categories = response;
})
.error(function (msg) {
console.log(msg);
});


$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category) //API to fetch some images associated with that **BroadCategory**
.success(function (response) {
$scope.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}

问题:问题是$scope.ads保留最后调用的 API 响应的值,因此 {{ ad.ad_type }}并且类似的广告属性具有所有相同的值(这是最后一个 BroadCategory 名称的响应)

如何使用最佳 Angular 方法解决此问题?

<h1>Expected Output: </h1>
<h4>BroadCategory1</h4>
BC1_data1
<br>BC1_data2


<h4>BroadCategory2</h4>
BC2_data1
<br>BC2_data2

<h1>Actual Output: </h1>
<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2

<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2

最佳答案

嗯,内部 ng-repeat 中生成的 html 都使用相同的 $scope.ads 列表。因此,如果更新,屏幕上的所有数据将仅显示 $scope.ads 的新值。

我要做的是将添加链接到类别。就像下面这样:

$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category)
.success(function (response) {
categoryInfo.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}

.

<div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>

<div ng-init="getImgForCategory(primaryItems)">
<div ng-repeat="ad in primaryItems.ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</div>

关于javascript - 我可以保留范围的旧值并将其他值更新为 AngualrJS 中的其他 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35015008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com