2015-12-21 23 views
0

請檢查這段代碼。我試圖從UI中獲得價值,但它未定義。它的代碼如下。當我在控制檯中打印這個值時,它會'未定義'。Angular-Js ng-model不接受值

UI代碼 -

<table class="table table-bordered table-striped container"> 
        <tr> 
         <td>First Name:</td> 
         <td><input type="text" ng-model="user.firstName"/></td> 
        </tr> 
        <tr> 
         <td>Last Name:</td> 
         <td><input type="text" ng-model="user.lastName"/></td> 
        </tr> 
        <tr> 
         <td>Email:</td> 
         <td><input type="text" ng-model="user.email"/></td> 
        </tr> 
        <tr> 
         <td>Mobile:</td> 
         <td><input type="text" ng-model="user.mobile"/></td> 
        </tr> 
        <tr> 
         <td><br/><button ng-click="addUser()" class="btn-panel-big">Add New User</button></td> 
        </tr> 
       </table> 

控制器代碼 -

$scope.addUser = function addUser() { 
     console.log("["+user.firstName+"]"); 
     $http.post(urlBase + 'users/insert/'+$scope.user) 
      .success(function(data) { 
      $scope.users = data; 
      $scope.user="";    
      }); 
     }; 

你能告訴什麼是錯的。我想將值存儲在單個對象中,然後將其發送到後端的基於控制器的休息中。

回答

0

使用$ scope.user來獲取用戶對象。

console.log("[" + $scope.user.firstName + "]"); 

而且很可能是以下行應該是

$http.post(urlBase + 'users/insert/', $scope.user) 

希望這有助於

+0

謝謝,我剛剛看到,但是當我在瀏覽器中發佈下面的問題時。這可能是什麼? '/ users/insert/[object%20Object] 500(內部服務器錯誤)' – Harshit

+0

如果要發佈數據,請使用$ http.post(urlBase +'users/insert /',$ scope.user)。注意,在$ scope.user之前不是+ – shakib

+0

我得到(404)未找到。當我使用'','而不是'+'。我在控制器中使用@PathVariable來接受對象值。 – Harshit

1

您是否將用戶對象初始化爲空對象? 例如var user = {}或$ scope.user = {}

+0

我沒有像在.js文件中提到的那樣定義。但是,如果我定義,我得到錯誤。兩種方式有什麼不同?用'var user = {}'我得到同樣的問題。但是,使用'$ scope.user = {}',它會帶來一些問題。 – Harshit

+0

使用$ scope.user = {}進行初始化;是你需要做的。你得到的錯誤是什麼?角度中的模型變量與控制器範圍相關聯,因此如果嘗試使用var user = {},則視圖和控制器之間將不存在綁定。 – Seonixx

+0

@Harshit:'$ scope.user = {}'有什麼問題? – ganeshwani

0

的問題是在適當設置範圍變量。