更新angularJS中的数据

时间:2014-11-06 19:43:44

标签: angularjs

我对角度js相当新,并且不确定如何谷歌我需要的条款。

我基本上有一个html页面,绑定到控制器。该页面将从mysql加载数据。

在我的控制器中,我在页面加载时有这样的代码:

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

页面上有一项功能,可以向数据库添加新条目。如何更新控制器,以便在将新内容添加到数据库后,它会自动显示?

我应该在angularjs术语中寻找什么关键字

2 个答案:

答案 0 :(得分: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});
        });

    }

}]);

答案 1 :(得分:0)

Angular会自动更新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。