2013-01-13 160 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中定義。我可以確認控制器正在工作,因爲控制器中的方法正在被調用。 –