AngularJS。如何用数据重新填充输入?

时间:2013-05-23 07:57:16

标签: jquery angularjs

使用ajax获取此数据后,是否可以以及如何将数据重新填充到网页上的输入?

当我按下“get”按钮时,我使用ajax(获取函数)获取数据并将其放入我的控制器的$ scope.data。但是在网页上你仍然会看到Nicolas Cage的输入为默认值。如何在“获取”功能后强行重新读取数据并重新填充输入?

我的网页是:

<div ng-controller="MyController">
  <input type="text" ng-model="data.firstname" required>
  <input type='text' ng-model="data.lastname" required>

  <form ng-submit="update()"><input type="submit" value="update"></form>
  <form ng-submit="get()"><input type="submit" value="get"></form>
</div>

我的js:

function MyController($scope) {
  // default data and structure
  $scope.data = {
    "firstname" : "Nicolas",
    "lastname" : "Cage"
  };

  $scope.get = function() {
    $.ajax({
        url: "/php/get_data.php?",
        type: "POST",
        timeout: 10000, // 10 seconds for getting result, otherwise error.
        error:function() { alert("Temporary error. Please try again...");},
        complete: function(){ $.unblockUI();},
        beforeSend: function(){ $.blockUI()},
        success: function(data){
            json_answer = eval('(' + data + ')');
            if (json_answer){
                $scope.data = json_answer;
            }
        }
    });
  };

  $scope.update = function() {
    $.ajax({
        url: "/php/update_data.php?",
        type: "POST",
        data: $scope.data,
        timeout: 10000, // 10 seconds for getting result, otherwise error.
        error:function() { alert("Temporary error. Please try again...");},
        complete: function(){ $.unblockUI();},
        beforeSend: function(){ $.blockUI()},
        success: function(data){ }
    });
  };

}

1 个答案:

答案 0 :(得分:0)

试试这个:

$scope.$apply(function () {
     $scope.data = json_answer;
});