Angular Js $ scope。$ apply不起作用

时间:2016-05-05 13:27:35

标签: javascript angularjs

我有一个表单,我通过它添加数据。数据更新的情况也是如此。我通过$ http post获取针对特定id的数据来填充表单。我更改了范围变量但没有获得修改后的值。以下是我的努力:

<input type="hidden" name="form_type" ng-model="formData.formType" ng-init="formData.formType = submit_button" value="{{submit_button}}"/>

<input type="hidden" name="student_id" ng-model="formData.studentId" ng-init="formData.studentId = student_id" value="{{student_id}}"/>

$scope.Edit = function (id) {
        $http({
                method: 'POST',
                url: 'process.php',
                data: $.param({action: 'fetch', id: id}),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (response) {
                if (!response.success) {
                    alert("something went wronge");
                    return false;
                } else {
                    $scope.formData = response.data;
                    $scope.student_id = response.data.id;
                    $scope.submit_button = 'Update';
                    $scope.$apply();
                }
            });
    };

enter image description here

1 个答案:

答案 0 :(得分:0)

这是在范围内安全应用的方式。

$scope.safeApply = function(fn) {
  var phase = this.$root.$$phase;
  if(phase == '$apply' || phase == '$digest') {
    if(fn && (typeof(fn) === 'function')) {
      fn();
    }
  } else {
    this.$apply(fn);
  }
};


$scope.safeApply(function() {
  alert('Now I'm wrapped for protection!');
});