2017-02-16 46 views
0
$rootScope.getPricesData = function (typ) { 
     var data = { 
      type: typ 
     } 
     $http({ 
      url: '...', 
      method: 'POST', 
      data: data 
     }).then(function (res) { 
      $rootScope.pricesData = res.data; 
      console.log(res); 
     }) 
    } 

而且它的作品好,HTML如何在兩個div中使用不同的數據提供相同的作用域?

<div ng-init="getPricesData('template')">info template</div> 
<div ng-init="getPricesData('subscription_month')">info subscription_month</div> 

,我在這兩個div的關於訂閱信息,請參閱(不tempate和訂閱)的控制檯我正確地看到這個數據,和函數被調用兩次(用於模板和訂閱)。

我覺得範圍覆蓋(但我不知道如何解決這個問題) 請幫忙

+0

,如果你宣佈路由器控制器以及在控制器會被調用兩次......除去 – Gopinath

+1

永遠不要嘗試使用rootscope它們中的任何一個那是一個不好的做法 –

+0

相反,你可以使用的指令 –

回答

1
  • 您可以使用JavaScript ternary operator處理方案

    $rootScope.getPricesData = function (typ) { 
        var data = { 
         type: typ 
        } 
        $http({ 
         url: '...', 
         method: 'POST', 
         data: data 
        }).then(function (res) { 
         if(typ == 'template') ? $scope.templatePricesData = res.data : $scope.subscriptionPricesData = res.data; 
        }) 
    } 
    
  • 可以創建一個空的對象,然後在成功響應的響應數據分配到一個對象的相應屬性。

    $scope.resData = {}; 
    $rootScope.getPricesData = function (typ) { 
        var data = { 
         type: typ 
        } 
        $http({ 
         url: '...', 
         method: 'POST', 
         data: data 
        }).then(function (res) { 
         $scope.resData[typ] = res.data; 
        }) 
    } 
    
+0

非常感謝你,你可以創建'$ rootScope.pricesData'和數組, – Kaker

0

我認爲這會覆蓋。一個可能的解決方案是讓你的$ rootScope的對象所以它可以像$ rootScope.pricesData [典型值]

相關問題