【问题标题】:Angular Js $scope.$apply doesn't workAngular Js $scope.$apply 不起作用
【发布时间】:2016-08-31 07:38:23
【问题描述】:

我有一个表单,我通过它添加数据。数据更新也是如此。我通过 $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();
                }
            });
    };

【问题讨论】:

  • 这篇文章的最佳答案可能会有所帮助:stackoverflow.com/questions/22733422/…
  • 但是为什么你需要打电话给$scope.$apply()呢?摘要循环是自动触发的,为什么要手动触发呢?
  • @iulian 因为在更改隐藏字段的范围变量后,在发布数据中没有得到更新的值。

标签: javascript angularjs


【解决方案1】:

这是安全应用在作用域中的方式。

$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!');
});

【讨论】:

    猜你喜欢
    • 2014-05-29
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多