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

时间:2016-01-26 13:33:05

标签: javascript angularjs angularjs-scope

好吧,我会尝试解释为什么我这样做的方法。为简单起见,我修改了代码。我想创建一个div,其中应该有<h4>BroadCategory Name</h4>并且在此标题下方,我正在调用一个API来获取与 BroadCategory名称相关联的一些图像

  <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>

我的控制器:

$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

1 个答案:

答案 0 :(得分:2)

嗯,内部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>