2013-01-13 155 views
0

奇怪的错误在这里。我有这样的形式:AngularJS范围变量不更新

<form name="newaccount" id="newaccount" ng-submit="doSubmit()"> 
<label>username</label> 
<input name="username" type="text" required ng-model="username"> 
<span ui-toggle="username.length > 15">Too long!</span> 
<label>name</label> 
<input name="name" type="text" required ng-model="name"> 
<label>e-mail</label> 
<input name="email" type="email" required ng-model="email" ui-validate> 
<label>password</label> 
<input name="password" type="password" required ng-model="password" ui-validate> 
<div style="text-align: center;"><br> 
<input type="submit"></div> 
</form> 

而这个控制器:

$scope.username = "f"; 
$scope.password = "f"; 
$scope.email = "f"; 
$scope.name = "f"; 
$scope.doSubmit = function(){ 
    //Transition to progress view 
    $scope.showLoginForm = false; 
    $scope.showCreateForm = false; 
    $scope.showLoading = true; 
    $scope.resultSuccess = false; 
    $scope.showResult = false; 
    $scope.loadingMessage = "Creating account..."; 
    $scope.resultReason = "Success!"; 

    //Send POST 
    $http({ 
     method: 'POST', 
     url: "php/createaccount.php", 
     data: { 
      "username": $scope.username, 
      "password": $scope.password, 
      "name": $scope.name, 
      "email": $scope.email 
     }} 
    ).success(function (data, status, headers, config) { 
      $scope.showLoading = false; 
      $scope.showResult = true; 
      $scope.resultSuccess = data === "success"; 
      if($scope.resultSuccess){ 
       $scope.resultReason = "Account created successfully!"; 
      }else{ 
       $scope.resultReason = data; 
      } 

     }).error(function (data, status, headers, config) { 
      $scope.showLoading = false; 
      $scope.showResult = true; 
      $scope.resultSuccess = false; 
      $scope.resultReason = data; 
     }); 
}; 

正如预期的那样, “F” 出现在每个字段。但是,如果您更改这些字段并提交表单,则服务器响应(在发布数据上使用print_r()),表明后端ALWAYS收到的JSON将包含“f”作为每个字段的值,而不是更改后的值。

示例: 使用用户名“测试”等

{"username":"f","password":"f","name":"f","email":"f"} 

因此,在$范围的值没有得到更新由于某种原因,当我在形式键入。是什么赋予了?

+0

是否有可能在每次提交表单时将字段赋值为“f”的代码运行? – akonsu

+0

也许,如果我没有提交任何内容,但删除了该部分! (从字面上看,没有键或值) –

+0

你能够在jsfiddle上设置此代码吗?不必发送POST,只需输出到控制台。 – akonsu

回答

1

代替$ HTTP调用内部分配个别$范围属性,使用“大对象”在您的范围:$ scope.person = {用户名:“F” ,...}。然后你可以发布该对象。

原来这个问题的具体问题是角度不会将范围变量的值写入范围变量,除非他们验证,在这种情况下,电子邮件没有正确验证。

0

是否使用'ng-app'和'ng-controller'来明确定义范围?

我无法在您的html中找到这两个指令。也许你没有把它作为问题的一部分。

其中我期望的样本结构:http://angularjs.org/#todo-html

+0

您在这里看到的代码在ng-app指令中的ng-view内。该控制器在app.js中定义。我可以确认控制器正在工作,因为控制器中的方法正在被调用。 –