2016-06-21 58 views
0

我做一個ajax(get)請求,並在角色「jobList」服務中獲得帶有json數據的承諾。

然後我用獲得的數據更新範圍。但我的問題是,更新一個範圍變量'X'我需要爲每個變量「readX」創建一個函數(見下文)。

有沒有辦法添加參數,就像在下面的代碼中的最後一個函數?

app.controller("JobListController", ['$scope', '$timeout', 'jobList', 
    function ($scope, $timeout, jobList) { 
     var readList = function (response) { 
      if (response) { 
       $timeout(function() { 
        $scope.list = response; 
        $scope.$apply(); 
       }); 
      } 
     }; 
     var readFamilies = function (response) { 
      if (response) { 
       $timeout(function() { 
        $scope.allFamilies = response; 
        $scope.$apply(); 
       }); 
      } 
     }; 
     var readRegions = function (response) { 
      if (response) { 
       $timeout(function() { 
        $scope.allRegions = response; 
        $scope.$apply(); 
       }); 
      } 
     }; 
     // !!! ----- HERE ------------- !!! 
     var readSomething = function (response, something) { 
      if (response) { 
       $timeout(function() { 
        $scope[something] = response; 
        $scope.$apply(); 
       }); 
      } 
     }; 

     jobList.get().then(readList); 
     jobList.getAll("allFamilies").then(readFamilies); 
     jobList.getAll("allRegions").then(readRegions); 
    }]); 

回答

1

首先,您可以簡化這些回調函數:假設回調發生在角度內(並且您使用的是$http),則不需要調用$timeout調用,也不需要調用$scope.$apply()。你也應該寫你的服務,只有當它返回數據時才能成功,如果失敗,就拒絕承諾;並且這樣你就不需要if因此每個回調可能只是作業。

如果您正在進行多次返回承諾的呼叫,您可以一起摺疊呼叫嗎?

$q.all([jobList.get(), jobList.getAll("allFamilies"), jobList.getAll("allRegions")]) 
.then(([list, families, regions]) => { 
    $scope.list = list; 
    $scope.allFamilies = families; 
    $scope.allRegions = regions; 
}); 

我這裏使用ES6語法:這是值得設置你的構建鏈使用類似babeljs,所以你可以使用簡單的回調速記符號。

如果你真的想分開打的電話(他們仍然在並行計算),你可以寫一個工廠產生的回調:

function assignToScope(name) { 
    return success; 

    function success(data) { 
     $scope[name] = data; 
    } 
} 
jobList.get().then(assignToScope('list')); 
jobList.getAll("allFamilies").then(assignToScope('allFamilies')); 
jobList.getAll("allRegions").then(assignToScope('allRegions')); 
0

試試這個:

jobList.get().then(function (response) { 
    readSomething(response); 
    }); 

和功能readSomething可以響應僅作爲輸入。

1

在獲取數據之前,您可以將所需屬性保存在scope變量中。

事情是這樣的:

$scope.property = "list"; 
jobList.get().then(readSomething); 

和你的功能現在將變成:

var readSomething = function (response) { 
      if (response) { 
       $timeout(function() { 
        $scope[$scope.property] = response; 
        $scope.$apply(); 
       }); 
      } 
     }; 

PS:

我猜你也可以使用封於做這樣的事情:

var readSomething = function (something) { 
      return function(response){ 
       if (response) { 
        $timeout(function() { 
         $scope[something] = response; 
         $scope.$apply(); 
        }); 
       } 
      } 
     }; 
+0

所以需要做2個呼叫的foreach功能,設置變量,然後調用函數... – Serge

+0

是啊,否則你可以看看封閉的方式,我編輯了我的答案 – gaurav5430

+0

我該如何使用readSomething呢? – Serge