2014-11-06 74 views
0

我對angular js相當陌生,但並不確定如何google我需要的術語。更新angularJS中的數據

我基本上有一個html頁面,綁定到一個控制器。這個頁面會從mysql加載數據。

在我的控制,我有這樣的代碼時,頁面加載速度:

thresholdNameSpace.controller("ThresholdController", ['$scope','$http', function ($scope, $http){ 
    $http.get('http://something.appspot.com/met').success(function(data){ 
    $scope.messages = data; 
}]); 

還有就是添加新條目的數據庫頁面上的功能。如何更新控制器,以便在將新內容添加到數據庫後自動顯示?

哪些關鍵字,我應該angularjs長期

+1

Angular自己做這件事,它是它的中心點之一。閱讀Angular數據綁定指南:https://docs.angularjs.org/guide/databinding – yerforkferchips 2014-11-06 19:46:19

回答

0

找好了,只是數據推到服務器併發送回一個響應......蠻力方法是將整個數據發送背背,或者只是在末尾附加當前的「消息」的消息對象

thresholdNameSpace.controller("ThresholdController", ['$scope','$http', function ($scope, $http){ 

    // get data 
    $http.get('http://something.appspot.com/met').success(function(data){ 
     // assuming messages is an array 
     $scope.messages = data; 
    }); 

    // create a function to push data up to the db, then update the view on success or failure appropriately 
    $scope.updateDatabase = function(param1, param2, param3...){ 
     var parameters = { 
      name: param1, 
      date: param2, 
      message: param3 
     } 
     $http.get('http://something.appspot.com/metUpdate', parameters).then(function(successResponse){ 
      console.log('successResponse', successResponse); 
      if($scope.messages) 
       $scope.messages.push({message: param3, person: param1, sent: param2}); // your object added to array 
     }, function(failureResponse){ 
      console.log('failureResponse', failureResponse); 
      // you can also push a error object which will be processed on the front end for proper display 
      $scope.messages.push({error: failureReason.data.errorMessage}); 
     }); 

    } 

}]); 
+0

數據庫可以從另一個用戶更新... – Thierry 2014-11-06 20:06:08

0

角自動更新HTML,你只需要更新$從數據庫scope.messages。例如,您可以每30秒獲取一次數據,使用$ interval。 類似這樣的:

var update = function() { 
    $http.get('http://something.appspot.com/met').success(function(data){ 
    $scope.messages = data; 
    } 
} 
$interval(update, 30000) 

不要忘記在控制器中注入$ interval。

+0

難道你不會說這是一個有點暴力和低效?此外,您需要確保在離開頁面時清除間隔。 – SoluableNonagon 2014-11-06 20:07:41

+0

當然@EliteOctagon,這只是一個例子,它需要適應......我不知道數據庫中有多少「消息」,以及有多少用戶等等。最好只添加新消息,當然。 – Thierry 2014-11-06 20:09:44