2016-06-09 75 views
0

我在下面有一個文本輸入,綁定到模型req.mod1,在更新模型中有一個去抖延遲,它調用pullData()函數。

<input type="text" class="form-control" ng-change="pullData()" ng-model-options="{debounce: 1000}" ng-model="req.mod1"> 

裏面的pullData()我有一個簡單$http.get要求,即提取數據,並在窗體更新一些其他領域。

$scope.pullData = function(){ 
    var pullingData = true; 
    if (!pullingData){ 
     $http.get('example.com/search/' + $scope.req.mod1).then(res) 
      ... 
      $scope.req.mod2 = res.data.mod2; 
      $scope.req.mod3 = res.data.mod3; 
      var pullingData = false; 
      ... 
    } 
} 

所產生的問題是,多個呼叫堆疊在彼此的頂部 - 我認爲 - 所以如果用戶恰好輸入文本,等待>1秒,並鍵入一些,呼叫會去與第一次輸入的文本。然後它會提取數據並用第一個res更新表單。我試圖跟蹤一個pullingData變種的請求。

關於如何處理真正動態搜索調用的任何想法?有新方法可以取消請求嗎?或者,也許只是告訴角度不斷覆蓋它?

在此先感謝。

回答

1

我覺得這是你所需要的 http://odetocode.com/blogs/scott/archive/2014/04/24/canceling-http-requests-in-angularjs.aspx

當您創建的請求..這就是所謂的Promise,所以你需要取消那是什麼。

事情是這樣的:

app.factory("movies", function($http, $q){ 
    var getById = function(id){ 
     var canceller = $q.defer(); 
     var cancel = function(reason){ 
      canceller.resolve(reason); 
     }; 
     var promise = $http.get("/api/movies/slow/" + id, { timeout: canceller.promise}) 
       .then(function(response){ 
        return response.data; 
       }); 
     return { 
      promise: promise, 
      cancel: cancel 
     }; 
    }; 
    return { 
     getById: getById 
    }; 
}); 
+0

會考慮這個方法 - 感謝 – zekone

0

當用戶輸入了一些搜索,你的應用程序應該總是由用戶輸入的搜索。這意味着你不應該取消用戶的輸入。

例如,用戶想要搜索一些關於'starwar'的內容,當他/她輸入'star'時,您會得到一些結果。如果現在取消後面輸入的'戰爭',結果不好。所以讓Angular重載結果。

而且,在你的代碼示例中的一些錯誤,當你調用pullData,它從來沒有經過檢查,如果:

$scope.pullData = function(){ 
    var pullingData = true; 
    // !pullingData is always false 
    if (!pullingData){ 
     $http.get('example.com/search/' + $scope.req.mod1).then(res) 

    } 
}