在.success和.error中使用范围变量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在.success和.error中使用范围变量相关的知识,希望对你有一定的参考价值。

我想在请求完成或失败时使用范围变量$ scope.field.name。我试图控制它,但它说未定义。如何在这些语法中访问范围变量?

usiApp.controller('fieldController',['$scope','$window','$http','field','$timeout','Profile','Referrence',function ($scope,$window,$http,field,$timeout,Profile,Referrence)
{
$scope.DoSomething = function(){
  $scope.field.class = 'fieldController'; //class of php method
  $scope.field.method = 'DoSomething'; //name of php method
  $scope.field.name = 'Ellsworth';
  field.getdata($scope.field)
      .success(function(data){
          if (data == true) {
              console.log($scope.field.name); //returns error this is the problem
          } else {
              console.log($scope.field.name); //returns error
          }
      })
      .error(function(data, status) {
          $scope.messages = data || "Request failed";
          $scope.status = status;
          console.log($scope.status);
          console.log($scope.messages);
          console.log($scope.field.name); //returns error
      });
}
}

我的field.getdata服务功能:

usiServices.factory('field', function($http) {
return {
    getdata : function(option) {
        return $http({
            method: 'POST',
            url: 'php/field-route.php',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
            data: $.param(option)
        });
      },
    }
 }
答案

你错过了$scope.field = {};。该行将创建一个空对象。创建对象后,您可以创建对象的属性($scope.field.class, $scope.field.method,$scope.field.name)。由于未创建对象,因此您将收到未定义的错误。在以下之前添加此$scope.field = {};行:

  $scope.field.class = 'fieldController'; //class of php method
  $scope.field.method = 'DoSomething'; //name of php method
  $scope.field.name = 'Ellsworth';

因此,最终更新的行将如下:

  $scope.field = {};
  $scope.field.class = 'fieldController'; //class of php method
  $scope.field.method = 'DoSomething'; //name of php method
  $scope.field.name = 'Ellsworth';

以上是关于在.success和.error中使用范围变量的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 .success 和 .error 在 Angularjs 中扩展 $q 承诺

在 AngularJS 中使用带有 Promises 的 success/error/finally/catch

关于ajaxFileUpload图片上传,success和error都触发的情况

FindWindowA() 返回 0,当我使用 GetLastError() 检查错误代码时,它也是 0 (ERROR_SUCCESS)

ThinkPHP页面跳转success与error方法

C#里error CS0136: 无法在此范围中声明名为“e”的局部变量或参数