2016-01-26 34 views
0

嗯,我會試着解釋我爲什麼要這樣做的方法。爲簡單起見,我修剪了代碼。我想創建一個DIV裏應該有<h4>BroadCategory Name</h4>和這個標題下面,我打電話一個API來獲取與BroadCategory名稱我可以保留範圍的舊值,並更新其他值在AngualrJS

<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 }}和類似的廣告屬性具有所有相同的值(這是對最後一個廣播類別名稱的響應)

我該如何用最好的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

@丹尼貝克:很酷。請記住這一點 –

+0

對於這種特殊情況,您接受的答案可能更合適,但是,是的,隔離範圍是「指令A中的數據被指令B中的數據破壞」的一般解決方案「 –

回答

2

那麼,在你的內心生成的HTML NG-重複所有使用相同的$ 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> 

+1

因此,您保存了它們所屬的「以前的」api響應,即在一個類別中。 – dendimiiii

+0

這真的很聰明的方法,謝謝:) –